如何使用Python定时向Discord频道发送消息?
解决Discord消息发送及定时问题
原代码问题排查
- 请求头键名错误:Discord API要求的是
Authorization(大小写敏感),而非authorisation - Token格式错误:若使用机器人Token,必须在前缀加上
Bot;若使用用户Token(不推荐,违反Discord服务条款),则前缀为Bearer - 请求数据格式错误:Discord API仅接受JSON格式数据,原代码用表单数据提交会失败
修正后的消息发送代码
import requests def send_message(token, channel_id, message): url = f'https://discord.com/api/v9/channels/{channel_id}/messages' headers = { 'Authorization': f'Bot {token}', # 机器人Token加Bot前缀,用户Token替换为Bearer {token} 'Content-Type': 'application/json' } data = {'content': message} response = requests.post(url, json=data, headers=headers) # 打印响应排查错误 if response.status_code == 200: print("消息发送成功") else: print(f"发送失败,状态码: {response.status_code}") print(f"错误详情: {response.text}") # 替换为你的实际信息 token = '你的机器人Token' channel_id = '目标频道ID' message = 'thanks' send_message(token, channel_id, message)
实现每分钟定时发送
方法1:基础循环+休眠
import time while True: send_message(token, channel_id, message) time.sleep(60) # 暂停60秒
方法2:使用schedule库(更灵活)
先安装依赖:pip install schedule
import schedule import time def job(): send_message(token, channel_id, message) # 配置每分钟执行一次任务 schedule.every(1).minutes.do(job) while True: schedule.run_pending() time.sleep(1)
关键注意事项
- 机器人必须被邀请到目标服务器,且拥有
发送消息的频道权限 - 禁止使用用户Token发送消息,会触发Discord账号封禁机制
- 高频发送需注意API速率限制,避免被临时限制访问
内容的提问来源于stack exchange,提问作者Yash Raja
相关产品推荐
相关产品推荐

