当我使用bot.polling()时,timed_messages永远不会被调用,是否有一种方法可以让这个东西工作,这样我就可以查找发送的消息并发送一个定时的自动消息
import telebot
import cryptocompare
from datetime import datetime
API_KEY = ""
bot = telebot.TeleBot(API_KEY)
@bot.message_handler(regexp="bitcoin")
def bitcoin(message):
price = cryptocompare.get_price('BTC', 'USD')
bot.reply_to(message, price['BTC']['USD'])
def timed_messages(prices, current_time):
if current_time == "9:00:00":
bot.send_message(-1001236909935, "Good Morning (9:00): \n" + prices)
if current_time == "12:00:00":
bot.send_message(-1001236909935, "Good Afternoon (12:00): \n" + prices)
if current_time == "15:00:00":
bot.send_message(-1001236909935, "Good Afternoon (15:00): \n" + prices)
if current_time == "18:00:00":
bot.send_message(-1001236909935, "Good Evening (18:00): \n" + prices)
if current_time == "00:00:00":
bot.send_message(-1001236909935, "Good Night (00:00): \n" + prices)
if __name__ == '__main__':
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
timed_messages(prices, current_time)
bot.polling()发布于 2022-02-10 17:26:08
您可以使用asyncio来实现您想要的结果。
先进口
import asyncio然后像这样修改代码:
async def timed_messages_worker():
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
timed_messages(prices, current_time)
await asyncio.sleep(1)
asyncio.create_task(timed_messages_worker)
asyncio.get_event_loop().run_until_complete(bot.polling())发布于 2022-04-10 17:31:19
您需要将异步与telebot的异步版本结合使用
https://stackoverflow.com/questions/71065355
复制相似问题