Discord Python Bot Schedule - python

I think I'm doing something wrong. If I try to use to print a message in console it does work but if I try to send a message to discord I can't get it to work.
import discord
import asyncio
from discord.ext import commands
import schedule
import time
TOKEN = 'xxx'
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print('Bot Online.')
async def job():
channel = client.get_channel('XXXX')
messages = ('test')
await client.send_message(channel, messages)
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
client.run(TOKEN)
I modified the code but I still get this message:
RuntimeWarning: coroutine 'job' was never awaited
self._run_job(job)

You need to use async on all functions, not just on the on ready. The function name is also called on_member_join.
#client.event
async def on_member_join(member):
await client.send_message(member, message)
The reason you have to dm the member and not send a message to a channel, is because no channel is specified.
Lets say you wanted to send a message to a specific channel you would have to do:
#client.event
async def on_member_join(member):
await client.send_message(client.get_channel('12324234183172'), message)
Replace the random number with the channel id.
If you want to read more about discord.py, you could read the docs or view a tutorial. Discord.py Docs
Note: Make sure to include import asyncio at the top of your page.
EDIT:
Another problem is that you did schedule.every(5).seconds.do(job). Change this line to: await schedule.every(5).seconds.do(job)

Related

Discord.py, I can't receive message with #client.command()

I can't receive message with #client.command().
This is what look like my code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='s!')
#client.command()
async def test(ctx):
print(ctx.author)
client.run('')
Thanks
Use ctx.channel.send() to send the message to the channel where the command was invoked from.
#client.command()
async def test(ctx):
ctx.channel.send(ctx.author.name)
The thing you are trying to do is the name of the author and printing out that.
If you want to send the message the user gave, you can do this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = 's!')
#client.event
async def on_message(message):
author = message.author
# "!test" is the command of taking the message. Change with yours.
if message.content.startswith('!test'):
print(message.content)
await test(author, message) #sends to a new method which shows message in channel.
async def test(author, message):
final_message = message.content[5:] #Slicing of the !test part. You also need to do it.
await message.channel.send(final_message)
client.run('')
Here,
"!test" is the command of taking the message. Change with yours.
Slice the command part to show the exact message.
Example

How do you get rid of "SyntaxError: 'await' outside function"

I am trying to make a discord bot change to online status
I have been using pycharm and terminal. I have tried reordering the code multiple different ways, but here is what I have right now
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
#client.event
async def on_ready():
print('Bot is ready.')
await client.run(bot token)
I also tried these:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
#client.event
async def on_ready():
print('Bot is ready.')
await client.run(bot token)
on_ready
and
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
#client.event
async def on_ready():
print('Bot is ready.')
await client.run(bot token)
on_ready
I got these errors:
:8: RuntimeWarning: coroutine 'on_ready' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
and
SyntaxError: 'await' outside function
Please help me get the bot online
Firstly, await cannot be outside of an async def function, the thing your awaiting is not indented enough to be inside the function on_ready.
Secondly, you shouldn't try to call on_ready manually, once the bot runs, it'll call on_ready itself.
Thirdly, Never put client.run inside of on_ready! Instead put it at the end of the file, if you do put it inside of on_ready, it'll never run.
so, this would be the ideal code:
#client.event
async def on_ready():
print('Bot is ready!')
client.run(TOKEN)
And as for storing your bot token, i would put it inside a database, like the replit or mongoDB database.
the await function is not needed for client.run()
put
async def on_ready():
print("Bot is ready.")
and put client.run at the end of the file. In my case, I use a file called config.py in which I have declared the value of token
token = "Enter your token here"
to import the variable, I did imported config with import config and since it's in config file, I entered client.run(config.token)
The print function needs to be intended another 4 spaces to be like:
async def on_ready():
print("Bot is ready.")
Try to install asyncio if the problem still occurs

How to make discord.py bot delete its own message after some time?

I have this code in Python:
import discord
client = commands.Bot(command_prefix='!')
#client.event
async def on_voice_state_update(member):
channel = client.get_channel(channels_id_where_i_want_to_send_message))
response = f'Hello {member}!'
await channel.send(response)
client.run('bots_token')
And I want the bot to delete its own message. For example, after one minute, how do I do it?
There is a better way than what Dean Ambros and Dom suggested, you can simply add the kwarg delete_after in .send
await ctx.send('whatever', delete_after=60.0)
reference
Before we do anything, we want to import asyncio. This can let us wait set amounts of time in the code.
import asyncio
Start by defining the message you send. That way we can come back to it for later.
msg = await channel.send(response)
Then, we can wait a set amount of time using asyncio. The time in the parentheses is counted in seconds, so one minute would be 60, two 120, and so on.
await asyncio.sleep(60)
Next, we actually delete the message that we originally sent.
await msg.delete()
So, altogether your code would end up looking something like this:
import discord
import asyncio
client = commands.Bot(command_prefix='!')
#client.event
async def on_voice_state_update(member, before, after):
channel = client.get_channel(123...))
response = f'Hello {member}!'
msg = await channel.send(response) # defining msg
await asyncio.sleep(60) # waiting 60 seconds
await msg.delete() # Deleting msg
You can also read up more in this here. Hope this helped!
This shouldn't be too complicated. Hope it helped.
import discord
from discord.ext import commands
import time
import asyncio
client = commands.Bot(command_prefix='!')
#commands.command(name="test")
async def test(ctx):
message = 'Hi'
msg = await ctx.send(message)
await ctx.message.delete() # Deletes the users message
await asyncio.sleep(5) # you want it to wait.
await msg.delete() # Deletes the message the bot sends.
client.add_command(test)
client.run(' bot_token')

Discordpy member history() function returning nothing

I've been trying to get my own message history using the member.history() method. But all i get is an empty asyncIterator that doesn't have anything in it.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".",intents=discord.Intents.all())
#client.event
async def on_ready():
print('Bot is ready')
#client.command()
async def test(ctx):
me = ctx.guild.get_member_named("Slade")
print(me)
async for message in me.history(limit=5):
print(message)
client.run("token would go here")
The only thing the code above prints is the ready message and my own discord name and tag.
What am i doing wrong?
Figured out the problem. For some reason both member.history() and user.history() function return private DM's with the bot not the guild message history.
Do the following
messages = await channel.history(limit=5).flatten()
this will return a list of messages.
So your function will be:
#client.command()
async def test(ctx):
me = ctx.guild.get_member_named("Slade")
print(me)
messages = []
for channel in ctx.guild.channels:
message = await channel.history(limit=5).flatten()
messages.append(message)
for message in messages:
print(message[0].content)
```
This returns for you 5 messages of every channel in your server.

How to send private message to member in on_member_join() discord.py?

This is what I have:
#client.command(pass_context=True)
#client.event
async def on_member_join(ctx, member):
print(f'{member} has joined a server.')
await ctx.send(f"Hello {member}!")
await ctx.member.send(f"Welcome to the server!")
I need the bot to send a private message containing rules and commands list when he joins.
Please help!
The event on_member_join() only accepts member as a valid parameter (see doc). Thus what you try to do: on_member_join(ctx, member) ,wont work. You need to use this instead: on_member_join(member).
If you used the event as follows:
#client.event
async def on_member_join(member):
await member.send('Private message')
You can send messages directly to members who joined the server. Because you get an member object using this event.
I don't know what happened, from one day to the next the bot stopped sending welcome messages to new members. But I was finally able to solve it.
I just had to add these two lines of code. intents = discord.Intents() intents.members = True Read
import discord
from discord.ext import commands
#try add this
intents=discord.Intents.all()
#if the above don't work, try with this
#intents = discord.Intents()
#intents.members = True
TOKEN = 'your token'
bot=commands.Bot(command_prefix='!',intents=intents)
#Events
#bot.event
async def on_member_join(member):
await member.send('Private message')
#bot.event
async def on_ready():
print('My bot is ready')
bot.run(TOKEN)

Categories

Resources