python - Telegram bot run_repeating 与 python-telegram-bot 库
问题描述
我刚刚开始发现如何用 python 构建一个机器人。我正在尝试在特定时间发送消息。似乎callback_minute函数不会接受多个参数。我阅读了很多示例,我阅读了有关run_repeating函数的文档,但我无法解决这个问题......
我的目标是动态地获取chat_id。有人可以帮助我吗?
import logging
import sys
import requests
import random
import datetime
import telegram.ext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import Updater, Filters, CommandHandler, MessageHandler, CallbackQueryHandler, ConversationHandler, CallbackContext
from lib import utils
class MonoBot:
def __init__(self):
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
# define a command callback function
def start(self, update, context):
#a = utils.search(self, update.message.from_user)
#context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text + a)
update.message.reply_text("write /lista top know what u can do...")
def echo(self, update, context):
context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text + " stuff")
def option(self, update, context):
button = [
[InlineKeyboardButton("text 1", callback_data="1")],
[InlineKeyboardButton("text 2", callback_data="2")],
[InlineKeyboardButton("text 3", callback_data="3")],
]
reply_markup = InlineKeyboardMarkup(button)
context.bot.send_message(chat_id=update.message.chat_id, text="scegli..", reply_markup=reply_markup)
def button(self, update, context):
query = update.callback_query
# context.bot.send_message(chat_id=query.message.chat_id, text="vitto " + query.data)
# use this below in order to hide option
context.bot.edit_message_text(chat_id=query.message.chat_id, text="vitto " + query.data,
message_id=query.message.message_id)
def get_location(self, update, context):
button = [[KeyboardButton("share location", request_location=True)]]
reply_markup = ReplyKeyboardMarkup(button)
context.bot.send_message(chat_id=update.message.chat_id, text="share location?", reply_markup=reply_markup)
def location(self, update, context):
lat = update.message.location.latitude
lon = update.message.location.longitude
context.bot.send_message(chat_id=update.message.chat_id, text="lat:" + str(lat) + " lon:" + str(lon),
reply_markup=ReplyKeyboardRemove())
#conversazione
def cancel(self, update: Update, context: CallbackContext) -> int:
print(update.message.from_user)
update.message.reply_text("by by :)", reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def cerca(self, update: Update, context: CallbackContext) -> int:
print("-"*40)
print(update.message.text)
word = update.message.text.split(" ")[1]
print("-"*40)
update.message.reply_text('https://www.google.com/search?q='+ word)
#return ConversationHandler.END
def lista(self, update: Update, context: CallbackContext) -> int:
update.message.reply_text("qua metto l\'elenco dei comandi che espongo...tipo\n- /cercaGOOGLE\n- /altrocomando")
print("-" * 40)
print(update.message)
print("-" * 40)
return CERCA
def reply(self, update: Update, context: CallbackContext) -> int:
user_input = update.message.text
update.message.reply_text(utils.search(self, user_input))
#return ConversationHandler.END
# i'm trying to send a message at certain time...
def callback_minute(self, update, context):
#-1001198785547
context.bot.send_message(chat_id=update.effective_chat.id, text="tempoooooo")
if __name__ == "__main__":
bot = MonoBot()
# first of all take token in order to authenticate
# check new messages --> polling
updater = Updater(token=sys.argv[1])
# allows to register handler --> command, text, video, audio, ...
dispatcher = updater.dispatcher
# CORE <<-----------
# create a command headler and command heandler to dispatcher ###ORDER LIST IS IMPORTANT!!
updater.dispatcher.add_handler(CommandHandler('start', bot.start))
updater.dispatcher.add_handler(CommandHandler('option', bot.option))
updater.dispatcher.add_handler(CommandHandler('location', bot.get_location))
updater.dispatcher.add_handler(MessageHandler(Filters.location, bot.location))
updater.dispatcher.add_handler(CallbackQueryHandler(bot.button))
#updater.dispatcher.add_handler(MessageHandler(Filters.text, bot.reply))
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
word, cmd, LOCATION, CERCA = range(4)
conv_handler = ConversationHandler(
entry_points=[CommandHandler('lista', bot.lista)],
states={
CERCA: [MessageHandler(filters=Filters.text, callback=bot.reply)],
},
fallbacks=[CommandHandler('exit', bot.cancel)],
)
dispatcher.add_handler(conv_handler)
# from here time issue..
j = updater.job_queue
j.run_repeating(bot.callback_minute, interval=60, first=10)
#t = datetime.time(6, 15, 00, 000000)
#j.run_daily(bot.timer, t, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)
#updater.dispatcher.add_handler(MessageHandler(Filters.text, bot.echo))
# start polling
updater.start_polling()
#updater.idle() # ???
我得到以下错误:
2021-02-15 22:21:04,527 - telegram.ext.dispatcher - DEBUG - Setting singleton dispatcher as <telegram.ext.dispatcher.Dispatcher object at 0x7f8719922040>
Traceback (most recent call last):
File "/home/vitto/PycharmProjects/monopattino/mono_bot.py", line 118, in <module>
j.run_repeating(bot.callback_minute, interval=60, first=10)
File "/home/vitto/PycharmProjects/monopattino/mono_env/lib/python3.8/site-packages/telegram/ext/jobqueue.py", line 291, in run_repeating
j = self.scheduler.add_job(
File "/home/vitto/PycharmProjects/monopattino/mono_env/lib/python3.8/site-packages/apscheduler/schedulers/base.py", line 434, in add_job
job = Job(self, **job_kwargs)
File "/home/vitto/PycharmProjects/monopattino/mono_env/lib/python3.8/site-packages/apscheduler/job.py", line 49, in __init__
self._modify(id=id or uuid4().hex, **kwargs)
File "/home/vitto/PycharmProjects/monopattino/mono_env/lib/python3.8/site-packages/apscheduler/job.py", line 180, in _modify
check_callable_args(func, args, kwargs)
File "/home/vitto/PycharmProjects/monopattino/mono_env/lib/python3.8/site-packages/apscheduler/util.py", line 401, in check_callable_args
raise ValueError('The following arguments have not been supplied: %s' %
ValueError: The following arguments have not been supplied: context
解决方案
尝试像这样update
删除callback_minute()
:
def callback_minute(self, context):
#-1001198785547
context.bot.send_message(
chat_id=update.effective_chat.id,
text='tempoooooo'
)
update
执行作业时没有送达。
推荐阅读
- html - 根据屏幕分辨率更改视频
- reactjs - 如何在 React js 中实现 slack Oauth-2.0?
- amazon-ec2 - 在 aws ec2 中,sudo: apt-get: command not found 错误
- android - Paging Library recyclerview 不显示更新数据(DB + Network)
- angular - 在 Angular 8 中使用 ngModel 和 ngModelOption 进行表单验证
- sql - Google Bigquery SQL UNNEST 和 STRING_AGG
- c3.js - 在c3 js中从下到上移动轴x
- c# - 如何在 C# 中将 Access 表复制到 SQL 表?
- python - 实现 K-Means 算法时 matplotlib 中的错误
- usb - STM32f4 USB cdc通信如何达到500kbps以上的速度