[英]Discord.py: How to send a message without using async and await
如何创建一个函数(没有异步),每次它(函数)在代码中的某处被执行时向特定通道发送消息?
def sendMsg():
channel = client.getChannel(Channel id)
message.channel.send("example message")
#excecuting the function
sendMsg()
什么都不做
async def on_message():
await message.channel.send("example message")
只有这个有效
所以我的问题是我是否可以修改顶部的代码使其工作?
确实需要异步来同步消息
如果您想将其作为 selfbot 响应消息,请执行
# Import's here
from discord.ext import commands
bot = commands.Bot(command_prefix='!', help_command=None, self_bot=True)
@bot.event
async def on_message(message):
if message.content.startswith("Hello"):
await message.channel.send(f"Hi @{message.author}")
bot.run('token ofc', bot=False)
无论如何,如果你想用机器人来做这个,请删除self_bot=True
和bot=False
如果您需要在异步上下文之外发送消息,则需要将任务添加到事件循环中。 请注意,当您“调用”协程时,您会得到实际的协程对象。 “调用”它实际上并没有运行协程,您需要将它放在事件循环中才能运行。
asyncio.get_event_loop().create_task(<coro>)
# use it like this
asyncio.get_event_loop().create_task(ctx.send('test'))
asyncio.get_event_loop().create_task(message.channel.send("example message"))
埃里克的回答是正确的。 此外,为了从 discord.py 中获取循环事件,您可以使用client.loop
来获取 discord.py 的 asyncio eventloop
也就是说,使用asyncio.run_coroutine_threadsafe(def,loop)
将任务安全地提交给 event_loop
client = discord.Client()
async def send_message_to_specific_channel(message='abc',id=123):
channel = client.get_channel(id)
await channel.send(message)
asyncio.run_coroutine_threadsafe(send_message_to_specific_channel('abc',123),client.loop)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.