如何让Python开发的Discord机器人本地发送消息(非私信用户)
实现Discord机器人本地输入消息并发送到频道的代码
要实现本地终端输入内容后,让机器人自动发送到Discord指定频道的功能,可以用discord.py结合线程监听输入来完成,以下是完整实现代码:
import discord import asyncio import threading # 替换为你的机器人Token TOKEN = "YOUR_BOT_TOKEN" # 替换为要发送消息的目标频道ID(整数类型) CHANNEL_ID = 123456789012345678 client = discord.Client(intents=discord.Intents.default()) def listen_for_input(): while True: message_content = input("输入要发送的消息:") if message_content.lower() == "exit": asyncio.run_coroutine_threadsafe(client.close(), client.loop) break # 获取目标频道 channel = client.get_channel(CHANNEL_ID) if channel: # 在机器人事件循环中执行发送消息操作 asyncio.run_coroutine_threadsafe(channel.send(message_content), client.loop) else: print("未找到指定频道,请检查CHANNEL_ID是否正确") @client.event async def on_ready(): print(f"机器人已登录,用户名:{client.user}") # 启动监听输入的线程 input_thread = threading.Thread(target=listen_for_input, daemon=True) input_thread.start() client.run(TOKEN)
使用说明:
- 安装依赖库:执行命令
pip install discord.py - 替换代码中的
YOUR_BOT_TOKEN为你的Discord机器人Token,CHANNEL_ID为目标频道的ID(需开启Discord开发者模式才能查看频道ID) - 运行代码后,在终端输入消息并回车,机器人就会将内容发送到指定频道;输入
exit可退出机器人
内容的提问来源于stack exchange,提问作者Austin Grayson
相关产品推荐
相关产品推荐

