0
votes

I've been trying to make a program that would run a discord bot and make it so whenever I press the right arrow key - the bot would send a message to a specific channel, but I get an error and I don't know how to do this.

import discord, os, pyperclip
from pynput import keyboard

client = discord.Client()
with open('token.txt', 'r') as f:
    token = f.readline()


def on_press(key):
    if key == keyboard.Key.right:
        myChannel = client.get_channel(763382459504132136)
        myChannel.send("sent to specific channel")

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")

with keyboard.Listener(on_press=on_press) as listener:
    client.run(token)
listener.join()

Here is what pops up in my terminal:

Logged in as Baku#8196 C:\Users\Venyl\Desktop\VS CODE\Code 2020\discordbot\discordbot.py:12: RuntimeWarning: coroutine 'Messageable.send' was never awaited myChannel.send("sent to specific channel") RuntimeWarning: Enable tracemalloc to get the object allocation traceback

1
you are missing a bunch of async and await statementsmousetail
I'm not that good at programming and I'm new to discord.py, can you elaborate?Venyl
Sending a channel is a asynchronious operation (as in, it will not complete immediately but rather at some unknown time in the future. Typically you await such statements, or use asyncio.create_task to run it in the backgroundmousetail
When I add async before def on_press and await before myChannel.send I get the same error but with 'on_press' instead of 'Messageable.send' and there's no "myChannel.send("sent to specific channel")"Venyl
Looks like whatever keyboard library you use doesn't like async code. You can use asyncio.create_task though be sure to store the task since it will be cancelled if garbage collectedmousetail

1 Answers

0
votes

I changed my part of code from myChannel.send("sent to specific channel") to client.loop.create_task(myChannel.send('sent to specific channel')) and it works.