gpt4 book ai didi

python-3.x - 为什么我无法通过 Discord.py 从函数发送消息?

转载 作者:行者123 更新时间:2023-12-02 03:47:58 26 4
gpt4 key购买 nike

我创建了一个脚本,它接受格式为 !notice [MM/DD/YY HH:mm], message, target 的消息,然后使用 threading.Timer 调用函数 在消息中给出的 UTC 时间调用它。

我遇到问题的是从这个函数发送消息,无论消息的输入如何,我似乎都无法从该函数发送消息。

见下文:

import discord
import asyncio
from datetime import *
import threading

client = discord.Client()

@client.event
async def on_message(message):
if message.content[:7].lower() == "!notice".lower():
try:
notice = [datetime.strptime(message.content[message.content.find("[")+1:message.content.find("]")], "%m/%d/%y %H:%M"), message.content.split(", ")[1], message.content.split(", ")[2]]
await client.send_message(message.channel, 'Created notice "'+notice[1]+'" to be sent to '+notice[2]+' at '+str(notice[0])+' UTC.')
threading.Timer((notice[0] - datetime.utcnow()).total_seconds(), lambda a=notice[1], b=notice[2]: func(a, b)).start()
print(str((notice[0] - datetime.utcnow()).total_seconds())+" seconds until message is sent")
except (ValueError, IndexError):
await client.send_message(message.channel, 'Incorrect Notice Format.\nMust be "!notice [MM/DD/YY HH:mm], Notice contents, Target".\nEG: "!notice [01/01/2017 12:00], This is a notice, Siren Raid Team".')

def func(message, target):
print("Func called")
for i in client.servers:
for c in i.channels:
client.send_message(c, target+message)

client.run(MY_SESSION_KEY)

这会返回“Func called”,因此我知道该函数正在被调用,但不会引发异常,并且我的聊天中不会发布任何消息。

我还尝试将 func 替换为:

async def func(message, target):
print("Func called")
for i in client.servers:
for c in i.channels:
await client.send_message(c, target+message)

但是这会引发异常:

RuntimeWarning: coroutine 'func' was never awaited

坦白说,我已经超出了我的能力范围。有什么原因导致这行不通吗?

我在网上看到asyncio不是线程安全的。但是,除非我误解了,否则我的第一个示例没有在函数中使用该库。是否仍然会造成问题?

最佳答案

discord.py 的 discord.Client.send_message是一个协程,必须等待,就像您在第二个代码片段中所做的那样。然而,threading.Timer不支持协程。您要找的是create_task ,它使您能够在事件循环上运行协程。由于您的协程所做的大部分工作都是 sleep (模仿 threading.Timer),因此您的 on_message 将继续运行,前提是您使用 asyncio.sleep > 而不是 time.sleep - 后者会阻止事件循环。这是一个示例,包括将参数传递给函数:

import asyncio

loop = asyncio.get_event_loop()

async def sleep_and_add(a, b):
await asyncio.sleep(3)
print(a, '+', b, 'is', a + b)

async def on_message():
# prepare arguments to your function
loop.create_task(sleep_and_add(2, 3))
# continue doing other things

关于python-3.x - 为什么我无法通过 Discord.py 从函数发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com