用django开发telegram机器人的简单应用
django-telegrambot的Python项目详细描述
用django开发telegram机器人的简单应用程序
更改日志
- important ver 1.0.0:如果从以前的版本升级,则必须更改如何包含django_telegrambot.urls并修改settings.py。
快速启动
安装django telegrambot:
pip install django-telegrambot
配置您的安装
在INSTALLED_APPS中添加django_telegrambot
#settings.py INSTALLED_APPS = ( ... 'django_telegrambot', ... )
设置你的机器人:
#settings.py #Django Telegram Bot settings DJANGO_TELEGRAMBOT = { 'MODE' : 'WEBHOOK', #(Optional [str]) # The default value is WEBHOOK, # otherwise you may use 'POLLING' # NB: if use polling you must provide to run # a management command that starts a worker 'WEBHOOK_SITE' : 'https://mywebsite.com', 'WEBHOOK_PREFIX' : '/prefix', # (Optional[str]) # If this value is specified, # a prefix is added to webhook url #'WEBHOOK_CERTIFICATE' : 'cert.pem', # If your site use self-signed #certificate, must be set with location of your public key #certificate.(More info at https://core.telegram.org/bots/self-signed ) 'BOTS' : [ { 'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token. #'ALLOWED_UPDATES':(Optional[list[str]]), # List the types of #updates you want your bot to receive. For example, specify #``["message", "edited_channel_post", "callback_query"]`` to #only receive updates of these types. See ``telegram.Update`` #for a complete list of available update types. #Specify an empty list to receive all updates regardless of type #(default). If not specified, the previous setting will be used. #Please note that this parameter doesn't affect updates created #before the call to the setWebhook, so unwanted updates may be #received for a short period of time. #'TIMEOUT':(Optional[int|float]), # If this value is specified, #use it as the read timeout from the server #'WEBHOOK_MAX_CONNECTIONS':(Optional[int]), # Maximum allowed number of #simultaneous HTTPS connections to the webhook for update #delivery, 1-100. Defaults to 40. Use lower values to limit the #load on your bot's server, and higher values to increase your #bot's throughput. #'POLL_INTERVAL' : (Optional[float]), # Time to wait between polling updates from Telegram in #seconds. Default is 0.0 #'POLL_CLEAN':(Optional[bool]), # Whether to clean any pending updates on Telegram servers before #actually starting to poll. Default is False. #'POLL_BOOTSTRAP_RETRIES':(Optional[int]), # Whether the bootstrapping phase of the `Updater` #will retry on failures on the Telegram server. #| < 0 - retry indefinitely #| 0 - no retries (default) #| > 0 - retry up to X times #'POLL_READ_LATENCY':(Optional[float|int]), # Grace time in seconds for receiving the reply from #server. Will be added to the `timeout` value and used as the read timeout from #server (Default: 2). }, #Other bots here with same structure. ], }
在url.py中包含django_telegrambot.urls(注意:如果从以前的版本升级,则必须更改如何包含django_telegrambot.urls。不要在这里设置前缀!):
#urls.py urlpatterns = [ ... url(r'^', include('django_telegrambot.urls')), ... ]
然后在项目中使用它,在应用程序中创建模块telegrambot.py。
#myapp/telegrambot.py # Example code for telegrambot.py module from telegram.ext import CommandHandler, MessageHandler, Filters from django_telegrambot.apps import DjangoTelegramBot import logging logger = logging.getLogger(__name__) # Define a few command handlers. These usually take the two arguments bot and # update. Error handlers also receive the raised TelegramError object in error. def start(bot, update): bot.sendMessage(update.message.chat_id, text='Hi!') def help(bot, update): bot.sendMessage(update.message.chat_id, text='Help!') def echo(bot, update): bot.sendMessage(update.message.chat_id, text=update.message.text) def error(bot, update, error): logger.warn('Update "%s" caused error "%s"' % (update, error)) def main(): logger.info("Loading handlers for telegram bot") # Default dispatcher (this is related to the first bot in settings.DJANGO_TELEGRAMBOT['BOTS']) dp = DjangoTelegramBot.dispatcher # To get Dispatcher related to a specific bot # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler([Filters.text], echo)) # log all errors dp.add_error_handler(error)
功能
多个机器人程序
管理仪表板位于/admin/django-telegrambot
管理命令的轮询模式(在本地计算机上运行bot的简单方法,不建议在生产中使用!)
^{tt9}$
贡献
欢迎使用补丁和错误报告,只是请保持与原始源的样式一致。
运行测试
代码真的有用吗?
source <YOURVIRTUALENV>/bin/activate (myenv) $ pip install -r requirements-test.txt (myenv) $ python runtests.py
示例应用程序
在sampleproject目录中有一个示例应用程序。以下是安装说明:
使用命令安装需求
pip install -r requirements.txt
将文件local_settings.sample.py复制为local_settings.py并编辑您的bot令牌
cp sampleproject/local_settings.sample.py sampleproject/local_settings.py
nano sampleproject/local_settings.py
运行django迁移
python manage.py migrate
运行服务器
python manage.py runserver
如果webhook已设置模式,请转到8
如果设置了polling模式,请在浏览器中打开http://localhost/
打开django telegram dashboardhttp://localhost/admin/django-telegrambot,按照管理命令botpolling的说明运行worker。然后转到10
要在本地测试webhook,请安装ngrok应用程序并运行命令
./ngrok http 8000
在local_settings.py文件中更改webhook_站点和允许的主机
使用django telegram dashboard中的telegram.me链接开始与您的机器人聊天在http://localhost/admin/django-telegrambot
历史记录
1.0.0(2017-05-25)
- 重要提示:如果从以前的版本升级,则必须更改如何包含django_telegrambot.url和settings.py。
- 添加了管理仪表板,可从/admin/django telegrambot获得
- 从管理命令添加了轮询模式(这是在本地计算机上运行bot的简单方法,不建议在生产中使用)
- 更多设置可用
- 改进的appconfig
- 改进的示例项目
0.2.6(2017-04-08)
- 改进的模块加载
- 添加了示例项目
0.2.5(2017-03-06)
- 修复与python telegram bot 5.1的兼容性
0.2.4(2016-10-04)
- 修复与django 1.10的兼容性
0.2.3(2016-07-30)
- 修复默认调度程序和bot
0.2.2(2016-07-27)
- 修复多个工人
0.2.1(2016-07-24)
- python telegram bot版本5.0的更新
0.2.0(2016-04-27)
- python telegram bot版本v4.0.1的更新
0.1.8(2016-03-22)
- 更新f或者在python telegram bot版本v3.4中反对
0.1.5(2016-01-28)
- 修复兼容性。
0.1.4(2016-01-28)
- 修复兼容性。
0.1.3(2016-01-28)
- 修复设置证书。
- 添加方法djangoTelegrambot.get bot();通过令牌或用户名获取bot实例。
0.1.2(2016-01-26)
- pypi上的第一个版本。