“discord.py”的”send message”函数

huangapple go评论52阅读模式
英文:

discord.py "send message" function

问题

I need to send a message in the discord channel based on a trigger that occurs in my program. My program runs in one main "while True" loop. Ideally, I'd like to call the "send_message(text, picture)" function.

What I have now:

class MyClient(discord.Client):
    async def on_ready(self):
        print(f'Logged on as {self.user}!')

    async def on_message(self, message):
        # This part works correctly, but that's not what I'm asking about.
        if str(message.author) != 'BOT' and message.content == "Show":
            print(f'Message from {message.author}: {message.content} in {message.channel.id}')
            is_success, buffer = cv2.imencode(".jpg", frame)
            io_buf = io.BytesIO(buffer)
            await message.channel.send(file=discord.File(io_buf, 'image.png'))

    async def my_send(picture_to_send, text_to_send):
        print("trying to send")
        c_id = ID
        channel_to = MyClient.get_channel(id=int(c_id))
        is_success, buffer = cv2.imencode(".jpg", picture_to_send)
        io_buf = io.BytesIO(buffer)
        await channel_to.send(content=str(text_to_send), file=discord.File(io_buf, 'image.png'))

def dis_start():
    intents = discord.Intents.default()
    intents.message_content = True

    client = MyClient(intents=intents)
    client.run('TOKEN')

dis_Call = threading.Thread(target=dis_start, daemon=True)
dis_Call.start()

When I try MyClient.my_send(frame, text), I receive the error "RuntimeWarning: coroutine 'MyClient.my_send' was never awaited". Maybe I'm trying to do it wrong; tell me how you would do it.

英文:

I need to send a message in the discord channel based on a trigger that occurs in my program. My program runs in one main "while True" loop. Ideally I'd like to call the "send_message(text, picture)" function.

What i have now:

class MyClient(discord.Client):
    async def on_ready(self):
        print(f'Logged on as {self.user}!')
   
    async def on_message(self, message):
        #This part work correctly, but that's not what I'm asking about.
        if str(message.author)!='BOT' and message.content=="Show":
            print(f'Message from {message.author}: {message.content} in {message.channel.id}')
            is_success, buffer = cv2.imencode(".jpg", frame)
            io_buf = io.BytesIO(buffer)
            await message.channel.send(file=discord.File(io_buf, 'image.png'))
    
    async def my_send(picture_to_send, text_to_send):
        print("trying to send")
        c_id=ID
        channel_to = MyClient.get_channel(id=int(c_id))
        is_success, buffer = cv2.imencode(".jpg", picture_to_send)
        io_buf = io.BytesIO(buffer)
        await channel_to.send(content=str(text_to_send), file=discord.File(io_buf, 'image.png'))

def dis_start():
    intents = discord.Intents.default()
    intents.message_content = True

    client = MyClient(intents=intents)
    client.run('TOKEN')

dis_Call = threading.Thread(target=dis_start, daemon=True)
dis_Call.start()

when i try MyClient.my_send(frame, text) i recieve error "RuntimeWarning: coroutine 'MyClient.my_send' was never awaited".
Maybe I'm trying to do it wrong, tell me how you would do it.

答案1

得分: 0

Since the my_send() method is asynchronous (marked with the async keyword), you need to use await to properly call it.

To fix your problem, you should modify the line where you call MyClient.my_send(frame, text) to be await MyClient.my_send(frame, text).

Additionally I noticed that your my_send() method is missing self keyword, which should be always the first parameter of class method.

async def my_send(self, picture_to_send, text_to_send):
英文:

Since the my_send() method is asynchronous (marked with the async keyword), you need to use await to properly call it.

To fix your problem, you should modify the line where you call MyClient.my_send(frame, text) to be await MyClient.my_send(frame, text).

Additionally I noticed that your my_send() method is missing self keyword, which should be always the first parameter of class method.

async def my_send(self, picture_to_send, text_to_send):

答案2

得分: 0

因为async/await函数的复杂性,我仍然不太明白如何正确执行client.my_send,我使用了一个非常糟糕但有效的“支架”(在英语中叫做这个吗?)。 Discord.py有一个标准的on_ready事件。我们在async def on_ready函数中添加一个While True循环,检查flag的值,如果flag==True,我们发送消息并将flag设置为False。不要忘记我们必须使用await asyncio.sleep(1)来确保循环不会运行得太快。由于我们使用了asyncio.sleep而不是time.sleep,所以不会减慢程序的运行,我也没有注意到CPU的严重负载。如何使用它?我们将消息文本放入任何全局变量中,然后调用flag=True。当if flag:触发时,它会在While True:中运行,程序将发送带有指定文本的消息。

在主程序中:

text_to_dis['text'] = our_text
text_to_dis['flag'] = True

在主程序中添加以上代码。

英文:

So, due to the complexity of async / await functions, I still did not understand how to correctly execute client.my_send, I made a very bad, but working "crutch" (is that what it's called in English?). Discord.py has a standard on_ready event. We add a While True loop to the async def on_ready function, where we check the value of flag, if flag==True, we send the message and do flag=False. Don't forget that we MUST use await asyncio.sleep(1) so that the loop doesn't run too fast. Since we used asyncio.sleep instead of time.sleep, we do not slow down our program, and I did not notice a serious load on the CPU. How to use it? We place the text of our message in any global variable, and call flag=True. The if flag: is fired, which spins in While True: and our program sends a message with the specified text.

async def on_ready(self):
    print(f'Logged on as {self.user}!')
    channel_to = self.get_channel(ID)
    while True:
        if text_to_dis['flag']:
            print("trying to send")
            text_to_send=''
            for t_i in text_to_dis['text']:
                text_to_send+=t_i+'     
            await channel_to.send(content=str(text_to_send))
            text_to_dis['flag']=False
        await asyncio.sleep(3)

In main program:

text_to_dis['text']=our_text
text_to_dis['flag']=True

huangapple
  • 本文由 发表于 2023年4月11日 07:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定