#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).
Related
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
Here is the full script:
from discord.ext.commands import Bot
import tracemalloc
tracemalloc.start()
client = Bot(command_prefix='$')
TOKEN = ''
#client.event
async def on_ready():
print(f'Bot connected as {client.user}')
#client.command(pass_context=True)
async def yt(ctx, url):
author = ctx.message.author
voice_channel = author.voice_channel
vc = await client.join_voice_channel(voice_channel)
player = await vc.create_ytdl_player(url)
player.start()
#client.event
async def on_message(message):
if message.content == 'play':
await yt("youtubeurl")
client.run(TOKEN)
When I run this script, it works fine. When I type play in the chat, I get this error:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\bot.py", line 26, in on_message
await yt("youtubeurl")
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 374, in __call__
return await self.callback(*args, **kwargs)
TypeError: yt() missing 1 required positional argument: 'url'
How do I fix this? So far all I have tried is added the argument * between ctx and url, which didn't fix it
It is not possible to "ignore" the context argument, why are you invoking the command in the on_message event?
You can get the context with Bot.get_context
#client.event
async def on_message(message):
ctx = await client.get_context(message)
if message.content == 'play':
yt(ctx, "url")
I'm guessing your commands aren't working cause you didn't add process_commands at the end of the on_message event
#client.event
async def on_message(message):
# ... PS: Don't add the if statements for the commands, it's useless
await client.process_commands(message)
Every command should be working from now on.
Reference:
Bot.get_context
Bot.process_commands
import discord
from discord.ext import commands
intents = discord.Intents(
messages = True,
guilds = True, reactions = True,
members = True, presences = True
)
bot = commands.Bot(command_prefix = "[", intents = intents)
#bot.event
async def on_ready():
print("Bot ready")
#bot.event
async def on_member_join(member):
print(f"{member} is ___")
#bot.event
async def on_member_remove():
print("xxx")
if member.id == 341212492212600832:
invitelink = discord.TextChannel.create_invite(max_uses=1,unique=True)
await member.send(f"you ___ bro. Here u go {inviteLink}")
bot.run("TOKEN")
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "C:\Users\Filbert\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)
TypeError: on_member_remove() takes 0 positional arguments but 1 was given
As the error said, on_member_remove takes 1 positional argument member
#bot.event
async def on_member_remove(member): # You forgot to pass it
# ...
Reference:
on_member_remove
Similar to on_member_join, on_member_remove gets passed member, as said in the docs. After fixing this issue, regenerate your token, as you included it in the original post.
Another issue: You shouldn't be creating an instance of discord.TextChannel. Instead, get that channel using bot.get_channel(id), and call create_invite on the TextChannel instance that get_channel returns.
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)