Pois
Pois

Reputation: 17

Unable to send a message to a discord channel discord.py

I wish to send a message using this simple background task. However, no errors come through on my python shell, but the message doesn't send.

import discord
import asyncio

client = discord.Client()

async def my_background_task():
    await client.wait_until_ready()
    counter = 0
    channel = discord.Object(id='791003444726988850')
    while not client.is_closed:
        counter += 1
        await client.send_message(channel, counter)
        await asyncio.sleep(60) # task runs every 60 seconds

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.loop.create_task(my_background_task())
client.run('MY BOT TOKEN')

Upvotes: 0

Views: 143

Answers (2)

Lemon.py
Lemon.py

Reputation: 819

First, add () after is_closed in your while loop condition: while not client.is_closed(): otherwise, your while loop will always return an object rather than a bool and the condition will not be met.

Then Change: channel = discord.Object(id='791003444726988850') to: channel = client.get_channel(791003444726988850)

lastly change: await client.send_message(channel, counter) to: await channel.send(counter)

Full code:

import discord
import asyncio

client = discord.Client()

async def my_background_task():
   await client.wait_until_ready()
   counter = 0
   channel = client.get_channel(791003444726988850)
   while not client.is_closed():
       counter += 1
       await channel.send(counter)
       await asyncio.sleep(60) # task runs every 60 seconds

@client.event
async def on_ready():
   print('Logged in as')
   print(client.user.name)
   print(client.user.id)
   print('------')

client.loop.create_task(my_background_task())
client.run('MY BOT TOKEN')

Upvotes: 1

bpiekars
bpiekars

Reputation: 53

I see you're using code similar to this, are you using a login token to run the bot as in client.run('token')?

Upvotes: 0

Related Questions