شما این محصولات را انتخاب کرده اید

سبد خرید

شناسه پست: 12957
بازدید: 3226

ساخت ربات تلگرام با پایتون

در این بخش زیر سعی داریم ساخت ربات تلگرام با پایتون را یاد بگیریم. برای این کار موارد زیر را به کار خواهیم گرفت:

Python 3
Python-telegram-bot
Public API Random Dog


قدم اول برای شروع

ابتدا قبلا از نوشتن دستورات در برنامه ی پایتون باید token برای ربات مربوطه ساخته شود. برای ایجاد token باید به AIP تلگرام دسترسی داشته باشیم.

ایجاد یک ربات جدید در BotFather

قبل از ساخت ربات باید فرایندثبت ان صورت گیرد .پس از ثبت ما به token دسترسی خواهیم داشت و با استفاده از آن می توان AIR تلگرام را به دست آورد. با فرستادن دستور /newbot در BotFather یک ربات جدید ایجاد کنید.

 

مراحل مربوطه را ادامه دهید تا نام کاربری و token مربوطه را دریافت کنید. با استفاده از می توانید به ربات خود دسترسی پیدا کنید :

https://telegram.me/YOUR_BOT_USERNAME

https://telegram.me/YOUR_BOT_USERNAME

Token به دست آمده باید شبیه کد زیر باشد:

************* ۷۰۴۴۱۸۹۳۱: AAEtbvgdrUTRcxsdcZ *************

نصب کتابخانه

با استفاده از دستور زیر کتابخانه ای برای این منظور تهیه می شود:

 


pip3 install python-telegram-bot

pip3 install python-telegram-bot

نوشتن برنامه

اینک سعی داریم اولین ربات را با استفاده از برنامه ی پایتون بسازیم . بعد از اجرای همه ی کد ها باید تصویر یک سگ بر روی مانیتور نمایش داده شود در صورتی که همه ی مراحل را به طور صحیح پیموده باشیم .

اهمیت کتابخانه

ابتدا همه ی کتابخانه های مربوطه ارد شود با استفاده از دستور زیر:

 


from telegram.ext import Updater, CommandHandler

import requests

import re

from telegram.ext import Updater, CommandHandler

import requests

import re

حال با استفاده از دستوز ریز به API و URL عکس دسترسی پیدا کنید :

 


contents = requests.get('https://random.dog/woof.json').json()

contents = requests.get('https://random.dog/woof.json').json()

داده ی jason با استفاده از URL زیر را به دست آورید.

https://random.dog/woof.json

نتیجه باید کی شبیه به کد زیر باشد:

 


{“url":"https://random.dog/*****.JPG"}

{“url":"https://random.dog/*****.JPG"}

حال image URL را به دست اورید:

 


image_url = contents['url']

image_url = contents['url']

حال با استفاده از تابع get_url() کد یاد شده را بپوشانید:

 


def get_url():

contents = requests.get('https://random.dog/woof.json').json()

def get_url():

contents = requests.get('https://random.dog/woof.json').json()

ارسال تصویر

برای ارسال یک پیام یا تصویر ما به در ایتم وپارامتر نیاز داریم . برای عکس پارامترهای :

 


the image URL
the recipient’s ID

با صدا زدن get_url() function. می توان به آدرس اورال عکس دست یافت:

 


url = get_url()

url = get_url()

recipient’s ID را نیز با استفاده از دستور زیر می توان به دست آورد :

 


chat_id = update.message.chat_id

chat_id = update.message.chat_id

حال که image URL and the recipient’s ID به دست امد ، زمان ان رسیده با دستور زیر عکس مربوطه ارسال شود:

 


bot.send_photo(chat_id=chat_id, photo=url)

bot.send_photo(chat_id=chat_id, photo=url)

کدمربوطه باید در تابعی به اسم bop قرار گیرد و ر نهایتکد به دست امدهباید مطابق کد زیر باشد .

 


def bop(bot, update):

url = get_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

def bop(bot, update):

url = get_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

برنامه ی اصلی

حال تابعی به اسم main را ایجاد کنید تا برنامه ی مربوطه اجرا شود . فرموش نکنید تاکن تولید شده باید بات اکن قبلی جایگزین شود :

 


def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

در نهایت باید کد زیر به نمایش آید :

 


from telegram.ext import Updater, InlineQueryHandler, CommandHandler

import requests

import re

def get_url():

contents = requests.get('https://random.dog/woof.json').json()

url = contents['url']

return url

def bop(bot, update):

url = get_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

from telegram.ext import Updater, InlineQueryHandler, CommandHandler

import requests

import re

def get_url():

contents = requests.get('https://random.dog/woof.json').json()

url = contents['url']

return url

def bop(bot, update):

url = get_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

اجرا کردن برنامه

اینک ساخت ربات تلگرام در پایتون به اتمام رسیده است . حال باید کارایی آن بررسی شود. نام آن را main.py سیو کنید و دستور زیر را اجرا کنید:

 


python3 main.py

python3 main.py

با نوشتن آدرس https://telegram.me/YOUR_BOT_USERNAME. به ربات تلگرامی خود دسترسی پیدا کنید و دستور /bopرا ارسال کنید. حال اگر عکس سگی بر روی ماتیتور ایجاد شود، همه ی مراحل با موفقیت پیموده شده است. در کنار این مقاله نگاهی به برنامه نویسی اندروید با پایتون نیز خواهیم داشت.

 

برطرف ساختن خطاها

با استفاده از این روش و کدهای یاد شده در مرحله ی بالا توانسته اید باتی را بسازید که هرزمان که بخواهید عکس های با مزه ای از سگ ها را برای شما ارسال خواهد کرد. با استفاده از آن نه تنها تصویری از سگ های با مزه خواهید داشت ، بلکه فیلم و گیفت های مختلفی از آن ها نیز در دسترس شما است.

برای حل این مشکل از regex استفاده خواهیم کرد. برای اینکه بتوانیم بین عکس ، فیلم و گیف های موجود ، تمایز قائل شویم بخش نهایی اورال مربوطه را در نظر می گیریم :

 

https://random.dog/*****.JPG

 

فایل های مربوطه را مشخص کرده یا به عبارت بهتر نامگذاری می کنیم:

 


allowed_extension = ['jpg','jpeg','png']

allowed_extension = ['jpg','jpeg','png']

حال regex را به کار می بریم تا فال مربوطه را از اورال موجود استخراج کنیم .

 


file_extension = re.search("([^.]*)$",url).group(1).lower()

file_extension = re.search("([^.]*)$",url).group(1).lower()

با استفاده از کد بالا تابعی تحت عنوان get_image_url() ساخته می شود .حال می توانیم فایل مربوطه را با دستور زیر به دست آوریم .

 


def get_image_url():

allowed_extension = [‘jpg’,’jpeg’,’png’]

file_extension = ‘’

while file_extension not in allowed_extension:

url = get_url()

file_extension = re.search(“([^.]*)$”,url).group(1).lower()

return url

def get_image_url():

allowed_extension = [‘jpg’,’jpeg’,’png’]

file_extension = ‘’

while file_extension not in allowed_extension:

url = get_url()

file_extension = re.search(“([^.]*)$”,url).group(1).lower()

return url

تغییر کد مربوطه

حال در مرحله ی آخر url = get_url() را در تابع bop() با url = get_image_url() جایگزاری کنید . کد نهایی باید به شکل زیر باشد.

 


from telegram.ext import Updater, InlineQueryHandler, CommandHandler

import requests

import re

def get_url():

contents = requests.get('https://random.dog/woof.json').json()

url = contents['url']

return url

def get_image_url():

allowed_extension = ['jpg','jpeg','png']

file_extension = ''

while file_extension not in allowed_extension:

url = get_url()

file_extension = re.search("([^.]*)$",url).group(1).lower()

return url

def bop(bot, update):

url = get_image_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

from telegram.ext import Updater, InlineQueryHandler, CommandHandler

import requests

import re

def get_url():

contents = requests.get('https://random.dog/woof.json').json()

url = contents['url']

return url

def get_image_url():

allowed_extension = ['jpg','jpeg','png']

file_extension = ''

while file_extension not in allowed_extension:

url = get_url()

file_extension = re.search("([^.]*)$",url).group(1).lower()

return url

def bop(bot, update):

url = get_image_url()

chat_id = update.message.chat_id

bot.send_photo(chat_id=chat_id, photo=url)

def main():

updater = Updater('YOUR_TOKEN')

dp = updater.dispatcher

dp.add_handler(CommandHandler('bop',bop))

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

اینک همه چیز به خوبی اجرا خواهد شد. حال شما یک ربات تلگرام را بااستفاده از برنامه ی پایتون ساخته اید .

 

اهمیت ساخت ربات تلگرام با پایتون

پیام رسان تلگرام بدون تردیدی در سال های اخیر با توجه به داشتن مزیتهای فوق العاده توانسته است جایگاه ویژگی را کسب نید و نسبت به سایر برنامه های هم نوع خود از توجه ویژه ای برخوردار باشد.

 

به همین دلیل سازندگان این برنامه سعی دارند با ارتقا دادن برخی از ویژگی های آن کارایی و استفاده ی آن را افزایش داده و از محبوبیت ویژه ای بهره مند شوند. وجود گزینه ی بات یا ربات تلگرامی در تلگرام نیز ان را به طور کافی از سایر برنامه ها مجزا ساخته است.

 

روش دنبال شده در بخش قبلی به ما کمک می کند با استفاده از برنامه ی پایتون بتوانیم ربات تلگرام ساخته و از ان بهره مند شویم. باهم نگاهی به مقاله ی آموزش علم داده (Data Science) با پایتون نیز داریم.

 

بات ها یک حساب کاربر خودکار بوده که به کاربر فرصت ی دهد کارهای جالبی انجام دهد به عنوان مثال زمانی که با استفاده از این برنامه با دوستان خود در ارتباط هستید می توانید به آسانی ویدیوها و عکس های مختلف را با دوستان خود به اشتراک گذارید.

البته بدون استفاده از آن ها روش های دیگری نیز برای اشتراک گذاری انواع عکس ها و فیلم ها است به عنوان بون استفاه از بات تلگرامی مجبور هستید مراحل زیر را انجام دهید:

 

وب‌سایت یوتیوب را در یک مرورگر وب باز کرده و بهبخش جستجو روید
ویدئویی که می‌خواهید ان را با دوستانتان اشتراک بگذارید، پیدا کنید
گزینه share via… را انتخاب کرده و با روش های مختلف اشتراک گذاری مواجه شوید
حال به تلگرام برگشته و لینک مربوطه را به اشتراک بگذارید.
عدم استفاده از ربات تلگرام

اگر چه این روش برای همه ی ما عادی است و عادت کرده ایم در بسیاری از مواقع مراحل یاد شده برای انتشار عکس و ویدیو ها در تلگرام را انجام دهیم ولی در برخی از مواقع حتی ممکن است مراحل یاد شده نیز با موفقیت صورت نگیرد.

به عنوان مثال زمانی که سرعت اینترنت پایین است در این صورت امکان وصل شده به فیلتر شکن برای ورود به یوتیوپ برای شما فراهم نیست . حال با استفاده از بات تلگرامی به آسانی در فضای تلگرام پیام های دلخواه را انتشار دهید . در این صورت کافی است مراحل زیر را دنبال کنید:

هنگام داشتن ارتباط با افراد زمانی که درون اپلیکیشن تلگرام هستید.
کلمه vid@ را به همراه ویدئویی که انتخاب کرده اید می توانید به اشتراک بگذارید
با زدن دکمه ارسال فیلم مربوطه در چت تلگرامی منتشر می شود
بات تلگرام

تردیدی نیست که روش دوم بسیار آسانتر می باشد ، و با استفاده از بات تلگرام می توانید در زمان کمتر پیام های مربوطه را انتقال دهید. برای ساخت بات تلگرام با استفاده از پایتون در ابتدا باید یک حساب ویژه در تلگرام داشته باشید.

زمانی که تلگرام را نصب کردید و یک حساب کاربری جدا ایجاد کردید در بخش جستجو دنبال کلمه ی botfather باشید . بعد از پیدا کن چت را در آن آغازکرده و دستور newbot/ را در ابتدا ارسال کنید ، مراحل بعدی به صورت خودکار تحت این بخش در اختیار شما قرار می گیرد. حال که مراحل لازم را در این بخش به اتمام رساندید موارد زیر را خواهید داشت:

توکن ویژه شما
URL برای API تلگرام
لینکی برای بات‌های تلگرام

موارد یاد شده نقطه شروع برای بهره مندی از بات تلگرامی است. در این مرحله بات تلگرامی ایجاد شده است ولی هنوز ما فرصت بهره مندی از آن را نداریم.

برنامه ی پایتون
پایتون از جمله زبان های برنامه نویسی ساده و در عین حال قدرتمند است که ما را قادر ساخته است بتوانیم با طراحی کدهای ویژه ، قدرت و کارایی نرم افزار های خود را ارتقا دهیم . امروزه از برنامه ی پایتون برای :

علم داده‌ها،
یادگیری ماشینی
خودکارسازی سامانه‌ها
توسعه وب
واسط‌های برنامه‌نویسی به طور وسیع استفاده می شود.

روش دیگر برای ساخت ربات تلگرام با پایتون

 

ابتدا باید یک فضای مجازی ایجاد شود

 


$ python -m venv botenv/

$ python -m venv botenv/

حال با استفاده از دستور زیر virtualenv را فعال کنید

 


$ source botenv/bin/activate

$ source botenv/bin/activate

کتابخانه ی ما به موارد زیر نیاز دارد

می توانیم با استفاده از دستور زیر آن ها نصب کنیم :

 


(telebot) $ pip install flask

(telebot) $ pip install python-telegram-bot

(telebot) $ pip install requests

(telebot) $ pip install flask

(telebot) $ pip install python-telegram-bot

(telebot) $ pip install requests

اینک پروژه ی مربوطه را به تنهایی جستجو کنید:

 


├── app.py

├── telebot

│├── credentials.py

│|.

│|you can build your engine here

│|.

│└── __init__.py

└── botenv

├── app.py

├── telebot

│├── credentials.py

│|.

│|you can build your engine here

│|.

│└── __init__.py

└── botenv

در بخش credentials.py ما به سه متغیر نیازمند خواهیم بود :

 


bot_token = "here goes your access token from BotFather"

bot_user_name = "the username you entered"

URL = "the heroku app link that we will create later"

bot_token = "here goes your access token from BotFather"

bot_user_name = "the username you entered"

URL = "the heroku app link that we will create later"

حال در app.py دستورات زیر را ثبت کنید:

 


# import everything

from flask import Flask, request

import telegram

from telebot.credentials import bot_token, bot_user_name,URL

global bot

global TOKEN

TOKEN = bot_token

bot = telegram.Bot(token=TOKEN)

حال بات مربوطه را ساختیم و می توانیم هر اقدامی را با انجام دهید

 


# start the flask app

app = Flask(__name__)

# import everything

from flask import Flask, request

import telegram

from telebot.credentials import bot_token, bot_user_name,URL

global bot

global TOKEN

TOKEN = bot_token

bot = telegram.Bot(token=TOKEN)

حال بات مربوطه را ساختیم و می توانیم هر اقدامی را با انجام دهید


# start the flask app

app = Flask(__name__)

URLتلگرام لازم برای /{token} با استفاده از دستور زیر صدا زده می شود که به پیام های فرستده شده به بات پاسخگو باشد:

 


@app.route('/{}'.format(TOKEN), methods=['POST'])

def respond():

# retrieve the message in JSON and then transform it to Telegram object

update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id

msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility

text = update.message.text.encode('utf-8').decode()

# for debugging purposes only

print("got text message :", text)

# the first time you chat with the bot AKA the welcoming message

if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

return 'ok'

@app.route('/setwebhook', methods=['GET', 'POST'])

def set_webhook():

# we use the bot object to link the bot to our app which live

# in the link provided by URL

s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))

# something to let us know things work

if s:

return "webhook setup ok"

else:

return "webhook setup failed"

@app.route('/{}'.format(TOKEN), methods=['POST'])

def respond():

# retrieve the message in JSON and then transform it to Telegram object

update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id

msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility

text = update.message.text.encode('utf-8').decode()

# for debugging purposes only

print("got text message :", text)

# the first time you chat with the bot AKA the welcoming message

if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

return 'ok'

@app.route('/setwebhook', methods=['GET', 'POST'])

def set_webhook():

# we use the bot object to link the bot to our app which live

# in the link provided by URL

s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))

# something to let us know things work

if s:

return "webhook setup ok"

else:

return "webhook setup failed"

حال همه چیز آماده شده است ، کافی است در این مرحله با دستور زیر یک صفحه وب جالب بسازیم :

 


@app.route('/')

def index():

return '.'

if __name__ == '__main__':

# note the threaded arg which allow

# your app to have more than one thread

app.run(threaded=True)

@app.route('/')

def index():

return '.'

if __name__ == '__main__':

# note the threaded arg which allow

# your app to have more than one thread

app.run(threaded=True)

بعد از دستور قبلی باید نسخه ی نهایی app.py به شکل زیر باشد:

 


import re

from flask import Flask, request

import telegram

from telebot.credentials import bot_token, bot_user_name,URL

global bot

global TOKEN

TOKEN = bot_token

bot = telegram.Bot(token=TOKEN)

app = Flask(__name__)

@app.route('/{}'.format(TOKEN), methods=['POST'])

def respond():

# retrieve the message in JSON and then transform it to Telegram object

update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id

msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility

text = update.message.text.encode('utf-8').decode()

# for debugging purposes only

print("got text message :", text)

# the first time you chat with the bot AKA the welcoming message

if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

 

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

return 'ok'

@app.route('/set_webhook', methods=['GET', 'POST'])

def set_webhook():

s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))

if s:

return "webhook setup ok"

else:

return "webhook setup failed"

@app.route('/')

def index():

return '.'

if __name__ == '__main__':

app.run(threaded=True)

import re

from flask import Flask, request

import telegram

from telebot.credentials import bot_token, bot_user_name,URL

global bot

global TOKEN

TOKEN = bot_token

bot = telegram.Bot(token=TOKEN)

app = Flask(__name__)

@app.route('/{}'.format(TOKEN), methods=['POST'])

def respond():

# retrieve the message in JSON and then transform it to Telegram object

update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id

msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility

text = update.message.text.encode('utf-8').decode()

# for debugging purposes only

print("got text message :", text)

# the first time you chat with the bot AKA the welcoming message

if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

return 'ok'

@app.route('/set_webhook', methods=['GET', 'POST'])

def set_webhook():

s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))

if s:

return "webhook setup ok"

else:

return "webhook setup failed"

@app.route('/')

def index():

return '.'

if __name__ == '__main__':

app.run(threaded=True)

برای اینکه Heroku تشخیص دهد کدام یک از کتابخانه ها به کار می رود فایل requirements.txt استفاده می کنیم . برای تولید فایل مربوطه دستور زیر را در نظر بگیرید :

 


pip freeze > requirements.txt

pip freeze > requirements.txt

حال با استفاده از Procfile مشخص کنید که نرم افزار مربوطه از کجا شروع به فعالیت کند. Procfile را با استفاده از دستور زیر بسازید:

 


web: gunicorn app:app

web: gunicorn app:app

با افزودن گزینه ی .gitignore دیگر نیازی به بروز رسانی آن نخواهید داشت.

برای Deploy ساختن، نیز مراحل زیر را ادامه دهید :

 


$ heroku login

$ heroku login

در صورتی که در بخش waiting for login با مشکل مواجه شدید ، دستور زیر را به کار گیرید:

 


$ heroku login -i

waiting for login را با دستور زیر نصب کنید :

 


$ git init

$ heroku git:remote -a {heroku-project-name}

$ heroku login -i

waiting for login را با دستور زیر نصب کنید :

 


$ git init

$ heroku git:remote -a {heroku-project-name}

حال نرم افزار را Deploy کنید:

 


$ git add .

$ git commit -m "first commit"

$ git push heroku master

$ git add .

$ git commit -m "first commit"

$ git push heroku master

اگه همه ی مراحل یاد شده صحیح باشد باید موارد زیر را بر روی مانیتور مشاهده کنید :


remote: -----> Launching...

remote: Released v6

remote: https://project-name.herokuapp.com/ deployed to Heroku

remote:

remote: Verifying deploy... done.

remote: -----> Launching...

remote: Released v6

remote: https://project-name.herokuapp.com/ deployed to Heroku

remote:

remote: Verifying deploy... done.

حال بات تلگرام مربوطه را دارید و می توانید با اضافه کردن برخی از موارد مثل گزینه typing بات تلگرامی خود را کاربردی تر کنید.

بات تلگرام

گزینه ی نوشتن به همره عکس های ارسالی ، طیق دستورات زیر به دست می آید.

با استفاده از تابعrespond() کد بعدی را به دست آورید :

 


if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendChatAction(chat_id=chat_id, action="typing")

sleep(1.5)

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendChatAction(chat_id=chat_id, action="upload_photo")

sleep(2)

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

if text == "/start":

# print the welcoming message

bot_welcome = """

Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.

"""

# send the welcoming message

bot.sendChatAction(chat_id=chat_id, action="typing")

sleep(1.5)

bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)

else:

try:

# clear the message we got from any non alphabets

text = re.sub(r"\W", "_", text)

# create the api link for the avatar based on http://avatars.adorable.io/

url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())

# reply with a photo to the name the user sent,

# note that you can send photos by url and telegram will fetch it for you

bot.sendChatAction(chat_id=chat_id, action="upload_photo")

sleep(2)

bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)

except Exception:

# if things went wrong

bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)

باصدا زدن تابع respond() می توانید لاگیک مربوطه را از سایر موارد به راحتی جدا کرده و از این طریق AI bot را بسازید:

 


├── app.py

├── telebot

│├── credentials.py

│├──ai.py

│|.

│|you can build your engine here

│|.

│└── __init__.py

└── botenv

├── app.py

├── telebot

│├── credentials.py

│├──ai.py

│|.

│|you can build your engine here

│|.

│└── __init__.py

└── botenv

در داخل ai.py :

 


def generate_smart_reply(text):

# here we can do all our work

return "this is a smart reply from the ai!"

def generate_smart_reply(text):

# here we can do all our work

return "this is a smart reply from the ai!"

حال آن را در app.py وارد کنید :

 


import re

from time import sleep

from flask import Flask, request

import telegram

From telebot.ai import generate_smart_reply

from telebot.credentials import bot_token, bot_user_name,URL

import re

from time import sleep

from flask import Flask, request

import telegram

From telebot.ai import generate_smart_reply

from telebot.credentials import bot_token, bot_user_name,URL

سپس دستور قبلی را در داخل کد respond() صدا بزنید :


def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id
msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode('utf-8').decode()
# for debugging purposes only
print("got text message :", text)
# here call your smart reply message
reply = generate_smart_reply(text)
bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)

def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)

chat_id = update.message.chat.id
msg_id = update.message.message_id

# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode('utf-8').decode()
# for debugging purposes only
print("got text message :", text)
# here call your smart reply message
reply = generate_smart_reply(text)
bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)

حال که مراحل مختلف ساخت ربات تلگرام با پایتون را فرا گرفته اید بهتر است با داشتن بات های مخصوص هنگام استفاده از تلگرام به آسانی پیام های خود را منتقل کنید .

 

دوستان عزیز همیشه با تلاش و تمرین در موضوعاتی که برای شما تهیه میکنم اگر انجام بدید چیزایی و که گفتم و میتونید به تمام خاصه هاتون برسید. مدیر تیم رباتسازی سلطان ویو و بنیانگذار چندین سایت حمیدرضا

همچنین جهت تهیه هاست پر سرعت و مناسب مخصوص ساخت ربات تلگرام میتوانید با کلیک کردن رو بنر زیر در سایت طلا هاست ثبت نام و سپس اقدام به خرید هاست حرفه ای آلمان نمایید :

نویسنده

مدیر سایت
با سلام بنده حمیدرضا مدیر و بنیانگذار سایت ویو پنل هستم که الان بیش از 5 سال در زمینه کدنویسی سورس ربات تلگرام در حال فعالیت بودم و همچنان هستم. سایت ویو پنل را هم با درخواست زیاد شما همکاران عزیز راه اندازی کردم تا بتوانم نیازهای شما را آماده کنم تا بتوانید مثل حرفه ای ها در تلگرام مشغول فعالیت باشید.