Command raised an exception: NameError: name 'challenge_player' is not defined - python

Me and my friend are trying to make a minigame kind of discord bot. I am trying to make a challenge command that takes the id of the user-specified and asks whether they want to accept or not.
#imports
import discord
from discord.ext import commands
#DISCORD PART#
client = commands.Bot(command_prefix = '-')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def challenge(ctx, member: discord.Member = None):
if not member:
await ctx.send("Please specify a member!")
elif member.bot:
await ctx.send("Bot detected!")
else:
await ctx.send(f"**{member.mention} please respond with -accept to accept the challenge!**")
challenge_player_mention = member.mention
challenge_player = member.id
#client.command()
async def accept(ctx):
if ctx.message.author.id == challenge_player:
await ctx.send(f"{challenge_player_mention} has accepted!")
else:
await ctx.send("No one has challenged you!")
#client.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
await client.process_commands(message)
client.run("token")
Everything is working fine except for the accept command.
Here is the error:
Traceback (most recent call last):
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/impec/Downloads/bots/epic gamer bot/epic_gamer.py", line 30, in accept
if ctx.message.author.id == challenge_player:
NameError: name 'challenge_player' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'challenge_player' is not defined
I cannot understand what I am doing wrong.

challenge_player is defined locally, in the challenge function so you can access it from the accept function.
You need to declare challenge_player outside of your function and add global challenge_player inside your functions, same thing with challenge_player_mention:
import discord
from discord.ext import commands
challenge_player, challenge_player_mention = "", ""
client = commands.Bot(command_prefix = '-')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def challenge(ctx, member: discord.Member = None):
global challenge_player, challenge_player_mention
if not member:
await ctx.send("Please specify a member!")
elif member.bot:
await ctx.send("Bot detected!")
else:
await ctx.send(f"**{member.mention} please respond with -accept to accept the challenge!**")
challenge_player_mention = member.mention
challenge_player = member.id
#client.command()
async def accept(ctx):
global challenge_player, challenge_player_mention
if ctx.message.author.id == challenge_player:
await ctx.send(f"{challenge_player_mention} has accepted!")
else:
await ctx.send("No one has challenged you!")
#client.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
await client.process_commands(message)
client.run("token")
PS: Don't share your bot token on internet! Anyone could access your bot with it and do whatever they want with it. You should generate another one and use it.

Related

discord.py music used to work but now im getting an error

im not sure what this error is or how to fix it. is it possible to fix or should i just not try.
i searched for this since other people had the same issue, but nothing helped my case.
A while back youtube removed dislike count and recently I tried running an old discord bot when i got this error:
Traceback (most recent call last):
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Judah Kriss\PycharmProjects\discord\main.py", line 25, in play
await player.queue(url, search=True)
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\DiscordUtils\Music.py", line 190, in queue
song = await get_video_data(url, search, bettersearch, self.loop)
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\DiscordUtils\Music.py", line 92, in get_video_data
dislikes = data["dislike_count"]
KeyError: 'dislike_count'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Judah Kriss\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'dislike_count'
why does the dislike count affect the bot?
the code:
import discord
from discord.ext import commands
import DiscordUtils
bot = commands.AutoShardedBot(command_prefix=">")
music = DiscordUtils.Music()
#bot.command()
async def join(ctx):
await ctx.author.voice.channel.connect() # Joins author's voice channel
#bot.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
#bot.command()
async def play(ctx, *, url):
player = music.get_player(guild_id=ctx.guild.id)
if not player:
player = music.create_player(ctx, ffmpeg_error_betterfix=True)
if not ctx.voice_client.is_playing():
await player.queue(url, search=True)
song = await player.play()
await ctx.send(f"Playing {song.name}")
else:
song = await player.queue(url, search=True)
await ctx.send(f"Queued {song.name}")
#bot.command()
async def pause(ctx):
player = music.get_player(guild_id=ctx.guild.id)
song = await player.pause()
await ctx.send(f"Paused {song.name}")
#bot.command()
async def resume(ctx):
player = music.get_player(guild_id=ctx.guild.id)
song = await player.resume()
await ctx.send(f"Resumed {song.name}")
#bot.command()
async def stop(ctx):
player = music.get_player(guild_id=ctx.guild.id)
await player.stop()
await ctx.send("Stopped")
#bot.command()
async def loop(ctx):
player = music.get_player(guild_id=ctx.guild.id)
song = await player.toggle_song_loop()
if song.is_looping:
await ctx.send(f"Enabled loop for {song.name}")
else:
await ctx.send(f"Disabled loop for {song.name}")
#bot.command()
async def queue(ctx):
player = music.get_player(guild_id=ctx.guild.id)
await ctx.send(f"{', '.join([song.name for song in player.current_queue()])}")
#bot.command()
async def np(ctx):
player = music.get_player(guild_id=ctx.guild.id)
song = player.now_playing()
await ctx.send(song.name)
#bot.command()
async def skip(ctx):
player = music.get_player(guild_id=ctx.guild.id)
data = await player.skip(force=True)
if len(data) == 2:
await ctx.send(f"Skipped from {data[0].name} to {data[1].name}")
else:
await ctx.send(f"Skipped {data[0].name}")
#bot.command()
async def volume(ctx, vol):
player = music.get_player(guild_id=ctx.guild.id)
song, volume = await player.change_volume(float(vol) / 100) # volume should be a float between 0 to 1
await ctx.send(f"Changed volume for {song.name} to {volume * 100}%")
#bot.command()
async def remove(ctx, index):
player = music.get_player(guild_id=ctx.guild.id)
song = await player.remove_from_queue(int(index))
await ctx.send(f"Removed {song.name} from queue")
bot.run('TOKEN')
thanks in advance :)
This error shows because the YouTube API no longer exposes the number of dislikes in their API so there is no key called dislikes. The issue has been raised but since the owner has abandoned the project there is not going to be a fix. However, another user has forked the repository and continued work on the project so here is what you can do:
Uninstall the old unsupported version:
pip uninstall DiscordUtils
Install the new branched version which no longer has this error:
pip install DiscordUtilsMod
Now change you code so that instead of
import DiscordUtils
Use
import DiscordUtilsMod

How can I ignore the ctx argument from discord.py?

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

how to define "#client.command"?

So basically I have this code:
import discord
import os
bot = commands.Bot(command_prefix = "!")
TOKEN = (os.getenv("TOKEN"))
client = discord.Client()
#client.event
async def on_message(message):
if message.content.startswith('!help'):
embedVar = discord.Embed(
title="Help Page", description="Under development", color=0x00ff00)
await message.channel.send(embed=embedVar)
#client.command()
#commands.has_any_role("Owner")
async def ban (ctx, member:discord.User=None, reason =None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "Breaking Rules"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
# await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{member} is banned!")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
When I run this I get the sequent error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
bot = commands.Bot(command_prefix = "!")
NameError: name 'commands' is not defined
Can someone please help me?
In the documentation for commands, it states to add this to your imports:
from discord.ext import commands
commands isn't defined because it isn't imported in your code put from discord.ext import commands at the top of your code. And, you don't need discord.Client() bc commands.Bot() is a subclass of it so please remove it for it is redundant. and finally, change client.command to bot.command to make the code work.

How to add role to person after saying smth

from discord.ext import commands
from discord.utils import get
client = discord.Client()
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
bot = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
print(f"{member} was given {role}")
client.run('NzY0MjA1MzA1MjQwMjIzNzQ0.X4C3pw.5RmXn1XswHCTWwOQ5i1v5lH5B6I')
when i run it and type something it gives me this:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\jpbay\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'member'
any help?
on_message event has only 1 argument, which is message. You cannot use 2 parameters in this event but you can access every attribute that member object has with using message.author.
Also, I don't recommend you to use discord.Client and discord.Bot at the same time. discord.Bot can do everything that discord.Client does.
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
client = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(message.guild.roles, name=ROLE)
await message.author.add_roles(role)
print(f"{message.author} was given {role}")
client.run('TOKEN')
NOTE:
You should change your token if you haven't changed yet.

Discord bot check if user is admin

Hi i'm new to python coding with discord and I have tried to make a command that tells the user if they are a admin or not but well... its not working in the slightest
#client.command(name="whoami",description="who are you?")
async def whoami():
if message.author == client.user:
return
if context.message.author.mention == discord.Permissions.administrator:
msg = "You're an admin {0.author.mention}".format(message)
await client.send_message(message.channel, msg)
else:
msg = "You're an average joe {0.author.mention}".format(message)
await client.send_message(message.channel, msg)
I then get this when I try to type whoami
Ignoring exception in command whoami
Traceback (most recent call last):
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **kwargs)
File "<stdin>", line 3, in whoami
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 846, in process_commands
yield from command.invoke(ctx)
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 374, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/home/python/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 54, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
If message.author.server_permissions.administrator doesn't work.
Change it to message.author.guild_permissions.administrator
Or try message.author.top_role.permissions.administrator, this will return you a bool.
One thing is, normally the server owner sets the administrator to the server top role, so this will work most of the time. But if they don't, the third sol won't work.
You can use the has_permissions check to see if a user has the administrator privilege.
We can then handle the error that failing that check will throw in order to send a failure message.
from discord.ext.commands import Bot, has_permissions, CheckFailure
client = Bot("!")
#client.command(pass_context=True)
#has_permissions(administrator=True)
async def whoami(ctx):
msg = "You're an admin {}".format(ctx.message.author.mention)
await ctx.send(msg)
#whoami.error
async def whoami_error(ctx, error):
if isinstance(error, CheckFailure):
msg = "You're an average joe {}".format(ctx.message.author.mention)
await ctx.send(msg)
Change
#client.command(name="whoami",description="who are you?")
async def whoami():
to
#client.command(pass_context=True)
async def whoami(ctx):
Then you can use ctx to get all kinds of stuff like the user that wrote it, the message contents and so on
To see if a User is an administrator do
if ctx.message.author.server_permissions.administrator: which should return True if the user is an an Administator
Your code should look like this:
import discord
import asyncio
from discord.ext.commands import Bot
client = Bot(description="My Cool Bot", command_prefix="!", pm_help = False, )
#client.event
async def on_ready():
print("Bot is ready!")
return await client.change_presence(game=discord.Game(name='My bot'))
#client.command(pass_context = True)
async def whoami(ctx):
if ctx.message.author.server_permissions.administrator:
msg = "You're an admin {0.author.mention}".format(ctx.message)
await client.send_message(ctx.message.channel, msg)
else:
msg = "You're an average joe {0.author.mention}".format(ctx.message)
await client.send_message(ctx.message.channel, msg)
client.run('Your_Bot_Token')

Categories