Python Telegram bot每间隔自动发送消息

时间:2021-07-16 02:16:57

标签: python-3.x telegram-bot

我有以下代码可以使用机器人发送消息。但是我怎么能每 1 小时发送一次这条消息呢?我需要帮助。谢谢。

import requests
import time
jokes = ['TEXT']

for joke in jokes:
   base_url = 'https://api.telegram.org/bot<<token>>/sendMessage?chat_id= CHATID&text=" {}"'.format(joke)
   requests.get(base_url
   time.sleep(15)

1 个答案:

答案 0 :(得分:0)

我为您创建了一个简单的循环处理程序。

import threading
import time
class loop:
    def wait(self, seconds):
        # This makes sure that when self.running is false it will instantly stop
        for a in range(seconds):
            if self.running:
                time.sleep(1)
            else:
                break

    def run(self, seconds):
        while self.running:
            # Runs function
            self.function()
            self.wait(seconds)

    def __init__(self, seconds, function):
        self.running = True
        self.function = function
        # Starts new thread instead of running it in the main thread
        # is because so it will not block other code
        self.thread = threading.Thread(target=self.run, args=(seconds,))
        self.thread.start()

你可以这样使用它:

import requests
import random
def sendJoke():
    # Gets random joke instead of looping through all of the jokes
    randomJoke = jokes[random.randrange(len(jokes))]
    base_url = 'https://api.telegram.org/bot<<token>>/sendMessage?chat_id= CHATID&text=" {}"'.format(randomJoke)
    requests.get(base_url)
# loop(seconds, function)
a = loop(3600, sendJoke)

您可以通过以下方式随时停止:

a.running = False