im fairly new to coding in general and recently started trying to code my own bot. Almost all of the tutorials i have seen use the ctx command however, whenever i use it i get this error:
"NameError: name 'ctx' is not defined"
Here is part of my code that uses the ctx command. The aim is to get it to delete the last 3 messages sent.
#client.event
async def purge(ctx):
"""clear 3 messages from current channel"""
channel = ctx.message.channel
await ctx.message.delete()
await channel.purge(limit=3, check=None, before=None)
return True
#client.event
async def on_message(message):
if message.content.startswith("purge"):
await purge(ctx)
client.run(os.environ['TOKEN'])
Full error:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 31, in on_message
await purge(ctx)
NameError: name 'ctx' is not defined
I'm hosting the server on repl.it if that makes any difference and as i said, im pretty new to coding so it's possible i have missed something very obvious, any help is appreciated. ^_^
A fix to that is:
async def purge(message):
await message.delete()
channel = message.channel
await channel.purge(limit=3)
#client.event
async def on_message(message):
if message.content.startswith("purge"):
await purge(message)
The problem is the on_message function uses message and not ctx. Replacing message with ctx wont work because im pretty sure the on_message cant use ctx
Related
I am trying to dm everyone in the server when the bot is added to the server using the on_join_guild().
The code for it
#client.event
async def on_guild_join(guild):
for member in guild.members:
await member.create_dm()
embedVar = discord.Embed(title="Hi", description="Hello", color=0x00ff00)
await member.dm_channel.send(embed=embedVar)
But whenever I add the bot to server, it dms everyone in the server which is expected but a error also pops in the console.
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\Khusi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File ".\time-turner.py", line 42, in on_guild_join
await member.create_dm()
File "C:\Users\Khusi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 110, in general
return getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'
What am I doing wrong?
After replicating your code, I found that your error only appears to happen if the bot tries to message itself. You would also get an error if your bot attempts to message another bot (Cannot send messages to this user). You can just use pass if your bot can't message a user or if it tries to message itself.
#client.event
async def on_guild_join(ctx):
for member in ctx.guild.members:
try:
await member.create_dm()
embedVar = discord.Embed(title="Hi", description="Hello", color=0x00ff00)
await member.dm_channel.send(embed=embedVar)
except:
pass
If the above still doesn't work, just as NerdGuyAhmad had said, you need to enable intents, at the very least member intents. View this link here: How do I get intents to work?
#client.event
async def on_message(message,channel):
if message.content.startswith("sa"):
await channel.send(message.channel, "as")
await client.process_commands(message)
This code should say as when I say sa. It detects the word but it doesn't respond. This is the error I'm getting:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\---\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'channel'
I'm thinking It might be an outdated code so I tried to change it as new as possible but I'm getting that error.
#client.event
async def on_message(message):
if message.content.startswith('sa'):
await message.channel.send('as')
await client.process_commands(message)
I don't know where you had got the code from but an old project I did in 2018 uses this function signature:
client = discord.Client()
#client.event
async def on_message(message):
if message.content.startswith("sa"):
await client.send_message(message.channel, "as")
However, since then, it looks like discord.py has migrated to a new version. Here is the new way to do it from the quickstart documentation:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
So what you want is probably the last few parts:
#client.event
async def on_message(message):
if message.content.startswith('sa'):
await message.channel.send('as')
EDIT
It looks like your code also got the process_commands part wrong. process_commands is a method of discord.ext.commands.Bot, not client. So it should be bot.process_commands(message).
Im new to working with discord.py, basically im simply trying to make my discord bot say something then delete the previous text, so for example I want to type "/say hello" then I want the bot to grab that, remove the prefix and just print "hello", Ive already googled and searched and found another guide but there was no follow up answers and when I tried the solutions they errored, below is the code im using
import discord
from discord.ext import commands
bot = discord.Client()
prefix = "/"
#bot.event
async def on_ready():
print("Online")
#bot.event
async def on_message(message):
args = message.content.split(" ")[1:]
if message.content.startswith(prefix + "say"):
await bot.delete_message(message)
await bot.send_message(message.channel, " ".join(args))
bot.run("token")
and this is the error the console prints out
C:\Users\unknownuser\anaconda3\envs\discordbot\pythonw.exe C:/Users/unknownuser/PycharmProjects/discordbot/bot.py
Online
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\unknownuser\anaconda3\envs\discordbot\lib\site-packages\discord\client.py", line 313, in _run_event
await coro(*args, **kwargs)
File "C:/Users/unknownuser/PycharmProjects/discordbot/bot.py", line 15, in on_message
await bot.delete_message(message)
AttributeError: 'Client' object has no attribute 'delete_message'
As I start learning the documentation and logic behind it I should start figuring it out for myself but this one has me stumped, Help would be appreciated
Looks like you're using a tutorial for an old version of discord.py.
There are some major changes in the most recent - rewrite - version.
Example for your code
# using the command decorator
#bot.command()
async def say(ctx, *, sentence):
await ctx.message.delete()
await ctx.send(sentence)
#############################################
# using the on_message event
#bot.event
async def on_message(message):
args = message.content.split(" ")[1:]
if message.content.startswith(prefix + "say"):
await message.delete()
await message.channel.send(" ".join(args))
else:
await bot.process_commands(message) # allows decorated commands to work
References:
Message.delete()
Bot.process_commands()
Messageable.send()
I am creating a bot with discord.py.
I would like to send an embed to a specific discord channel when the bot is ready. To do that, here is my code:
import discord
client = discord.Client()
logchannel = client.fetch_channel(692934456612487199)
#client.event
async def on_ready():
print(f'Ticket Tool active as {client.user}')
embed = discord.Embed(title="**Jokz' Ticket Tool**", color=0xff0000, description="Started Successfully!")
embed.set_footer(text="JokzTickets | #jokztools",icon_url="https://pbs.twimg.com/profile_images/1243255945913872384/jOxyDffX_400x400.jpg")
embed.set_thumbnail(url="https://gifimage.net/wp-content/uploads/2017/10/check-mark-animated-gif-12.gif")
await logchannel.send(embed=embed)
client.run(key)
When I run this, I get the following error:
PS C:\Users\jokzc\Desktop\jokzticketspy> py index.py
Ticket Tool active as Jokz' Tools#5577
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\jokzc\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "index.py", line 15, in on_ready
await logchannel.send(embed=embed)
TypeError: send() takes no keyword arguments
What would the correct way to format this be?
So I ended up figuring out that it worked if I changed the function from client.fetch_channel to client.get_channel and I needed to put this in the actual on_ready function! The reason for this is because the client cannot get or fetch the channel until the client is actually ready.
The corrected code looks like this:
#client.event
async def on_ready():
logchannel = client.get_channel(692934456612487199)
print(f'Ticket Tool active as {client.user}')
embed = discord.Embed(title="**Jokz' Ticket Tool**", color=0x00ff00, description="Started Successfully!")
embed.set_footer(text="JokzTickets | #jokztools",icon_url="https://pbs.twimg.com/profile_images/1243255945913872384/jOxyDffX_400x400.jpg")
embed.set_thumbnail(url="https://gifimage.net/wp-content/uploads/2017/10/check-mark-animated-gif-12.gif")
await logchannel.send(embed=embed)
#client.event
async def on_ready():
channelid = client.get_channel(id)
botname = client.user.name
print('message ' + botname)
embed = discord.Embed(title=f"Text", description="Text", color=discord.Color.red())
embed.set_footer(text="Your text", icon_url="URL of icon")
embed.set_thumbnail(url="Url")
await channelid.send(embed=embed)
I'm trying to create a bot that greets a user that joins a server. But make it so that the person is greeted in the server itself rather than as a DM (which most tutorials I've found teach you how to do).
This is what I've come up with so far.
#bot.event
async def on_member_join(member):
channel = bot.get_channel("channel id")
await bot.send_message(channel,"welcome")
but, it doesn't work and instead throws up this error.
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\Lenovo\Documents\first bot\bot.py", line 26, in
on_member_join
await bot.send_message(channel,"welcome")
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-
packages\discord\client.py", line 1145, in send_message
channel_id, guild_id = yield from self._resolve_destination(destination)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-
packages\discord\client.py", line 289, in _resolve_destination
raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel,
User, or Object. Received NoneType
You aren't passing the correct id to get_channel, so it's returning None. A quick way to get it would be to call the command
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def get_id(ctx):
await bot.say("Channel id: {}".format(ctx.message.channel.id))
bot.run("TOKEN")
You could also modify your command to always post in a channel with a particular name on the server that the Member joined
from discord.utils import get
#bot.event
async def on_member_join(member):
channel = get(member.server.channels, name="general")
await bot.send_message(channel,"welcome")
The answer by Patrick Haugh is probably your best bet, but here are a few things to keep in mind.
The Member object contains the guild (server), and the text channels the server contains.
By using member.guild.text_channels you can ensure the channel will exist, even if the server does not have a 'general' chat.
#bot.event
async def on_member_join(member):
channel = member.guild.text_channels[0]
await channel.send('Welcome!')
Try this:
#bot.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.channels, name='the name of the channel')
await channel.send(f'Enjoy your stay {member.mention}!')