利用Python打造一个自动发送消息的botBot()
发布时间:2023-12-11 06:42:14
要打造一个自动发送消息的bot,可以使用Python编程语言和基于Web的库。下面是一个示例代码:
import requests
import time
class BotBot:
def __init__(self, access_token):
self.access_token = access_token
def send_message(self, recipient_id, message):
url = f"https://api.telegram.org/bot{self.access_token}/sendMessage"
payload = {
"chat_id": recipient_id,
"text": message
}
response = requests.post(url, data=payload)
return response.json()
def send_messages(self, recipient_ids, message):
for recipient_id in recipient_ids:
self.send_message(recipient_id, message)
time.sleep(1) # 增加1秒的延迟,以防止频繁发送
# 使用示例
bot = BotBot("<YOUR_ACCESS_TOKEN>")
recipient_ids = ["user_id_1", "user_id_2", "user_id_3"]
message = "Hello, World!"
bot.send_messages(recipient_ids, message)
上述代码使用了Telegram的Bot API来发送消息。首先,你需要创建一个Telegram bot,并获得一个访问令牌(access token)。然后,将令牌传递给BotBot类的构造函数。
send_message方法将通过POST请求将消息发送给指定的用户或聊天。send_messages方法允许你同时向多个用户发送消息。为了避免频繁发送,我们在每个消息发送之间增加了1秒的延迟。
你需要将"<YOUR_ACCESS_TOKEN>"替换为你获得的真实访问令牌,并修改recipient_ids为你要发送消息的用户或聊天的ID。
这个示例代码只是一个基本功能实现的简单示例。你可以根据实际需求进行扩展,如添加其他API功能、处理异常等。
总结起来,使用Python可以轻松地打造一个自动发送消息的bot。这个bot可以通过使用Telegram的Bot API来实现,你只需获取访问令牌,并使用Python的requests库来发送消息。
