When i'm running the code
I get an error saying
`
We have logged in!
Ignoring exception in on_interaction
Traceback (most recent call last):
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/bot.py", line 815, in process_application_commands
command = self._application_commands[interaction.data["id"]] # type: ignore
KeyError: '1046690510644973609'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/bot.py", line 1167, in on_interaction
await self.process_application_commands(interaction)
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/bot.py", line 837, in process_application_commands
await self.sync_commands(check_guilds=[guild_id])
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
File "/home/jivesh/.local/lib/python3.10/site-packages/discord/http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
while running the code
import discord
from discord import Option
from discord.ext import commands
from discord.ext.commands import MissingPermissions
import json
import asyncio
import aiosqlite
bot = discord.Bot()
servers = ["1046334284761411615","935234857783681054"] #server ids
#bot.event
async def on_ready():
print("We have logged in!")
bot.db = await aiosqlite.connect('warns.db')
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS warns(user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
await bot.db.commit()
async def addwarn(ctx, reason, user):
async with bot.db.cursor as cursor:
await cursor.execute("INSERT INTO warns (user, reason, time, guild) VALUES (?,?,?,?)", (user.id, reason, int(datetime.datetime.now().timestamp()), ctx.guild.id))
await bot.db.commit()
#bot.slash_command(guild_ids = servers, name = "warn", description= "Warns a user")
#commands.has_permissions(manage_messages=True,administrator = True)
async def warn(ctx, user: Option(discord.Member, description = "Whom do you want to warn?"),reason: Option(str, description = "Why?", required = False)):
if user.id == ctx.author.id:
await ctx.respond("BRUH! You can't warn yourself!")
elif user.guild_permissions.administrator:
await ctx.respond("Stop trying to warn an admin! :rolling_eyes:")
else:
await addwarn(ctx, reason, user)
await ctx.respond(f"Warned {member.mention} for {reason} by {user.mention}")
bot.run('')
Please help me with giving the corrected version of the code.
please ignore these character as i am trying to escape the error of stackoverflow "It looks like your post is mostly code; please add some more details."
Related
I have this code for my PyCord bot,
from discord.ext import commands
import discord
from discord_components import *
bot = commands.Bot(command_prefix='>')
#bot.event
async def on_ready():
print("Bot Ready")
#bot.command()
async def lab(ctx):
ctx.reply("Welcome to the Lab")
responses = ['yes.gif','no.gif','laugh.gif','ugh.gif']
#bot.event
async def on_message(message):
if message.author.bot == False and message.channel.id == 798909171587874867:
gif = random.choice(responses)
await message.reply(file=discord.File(gif))
But when I run the program and try to do the slash command, first it doesn't appear and then I get this error:
Ignoring exception in on_connect
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/bot.py", line 1045, in on_connect
await self.sync_commands()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/bot.py", line 555, in sync_commands
registered_guild_commands[guild_id] = await self.register_commands(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/bot.py", line 420, in register_commands
desynced = await self.get_desynced_commands(guild_id=guild_id)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/bot.py", line 252, in get_desynced_commands
registered_commands = await self.http.get_guild_commands(self.user.id, guild_id)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/http.py", line 332, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
These are my Discord permissions in the developer portal
I fixed this by adding application.commands as #Chuaat said in the Oauth2 and link generator page.
So I'm new to python, and I wanted to make an economy bot. I followed some tutorials, but my program does not work, it says "users" isn't defined, even though I think I defined it.
My code:
import discord
from discord.ext import commands
import json
client = commands.Bot(command_prefix='`')
#client.event
async def on_ready():
print("We have logged into this server as {0.user}".format(client))
#client.command()
async def balance(ctx):
await open_account(ctx.author)
users = await get_bank_data() #Here's where I think I defined it
purse_amt = users[str(user.id)]["purse"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f"{ctx.author.name}'s balance", color=discord.color.purple())
em.add.field(name="Purse", value=purse_amt)
em.add.field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
async def open_account(user):
await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)]["purse"] = 0
users[str(user.id)]["bank"] = 0
with open("mainbank.json", "w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("mainbank.json", "r") as f:
users = json.load(f)
return users
client.run(token)
Edit: Here is my error message, I'm not sure what all of it means, but I think the main thing it's saying is that "users" is not defined:
Ignoring exception in command balance:
Traceback (most recent call last):
File "C:\Users\Cyfix", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Cyfix", line 14, in balance
await open_account(ctx.author)
File "C:\Users\Cyfix", line 29, in open_account
if str(user.id) in users:
NameError: name 'users' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Cyfix", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Cyfix", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Cyfix", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'users' is not defined
You meant to keep hold of the users returned:
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
...
I have started making Ticket bot using discord.py but I have an error in my code and I don't know how to solve it. Embed and reacting to message work but when I try to react everythings crashes. Here is my error:
Ignoring exception in command ticket:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\HP\Desktop\222\dscbot-dscbot.py", line 150, in ticket
if reaction == '📩':
NameError: name 'reaction' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\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: NameError: name 'reaction' is not defined
I hope someone have and idea how to fix this, here is my current code:
import discord
from discord.ext import commands
from discord.utils import get
from discord import Embed, Color
import DiscordUtils
import os
from discord.ext.commands import has_permissions, MissingPermissions
import json
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = "-", intents = intents)
client.remove_command("help")
#client.command(pass_context=True)
async def ticket(ctx):
guild = ctx.guild
embed = discord.Embed(
title = 'Ticket system',
description = 'React 📩 to make a ticket.',
color = 0
)
embed.set_footer(text="ticket system")
msg = await ctx.send(embed=embed)
await msg.add_reaction("📩")
reaction = await msg.fetch_message(msg.id)
await client.wait_for("reaction_add")
await client.wait_for("reaction_add")
if reaction == '📩':
await guild.create_text_channel(name=f'ticket - {reaction.author.name}')
ps: I am new to discord.py
reaction = await msg.fetch_message(msg.id) is just giving you msg. You instead need to take the reaction from await client.wait_for("reaction_add")
Take a look at wait_for. You implement a check (Which is where the reaction is) to see if the reaction is a mailbox.
You need to create a new function that creates a channel if the reaction is a mailbox, then pass that into client.wait_for.
def check(reaction, user):
return str(reaction) == '📩' and ctx.author == user
await client.wait_for("reaction_add", check=check)
await guild.create_text_channel(name=f'ticket - {ctx.author}')
You didn't define reaction, that's why this error is raised.
Take a look at this post to find out how to fetch reactions from messages.
I am making a bot in python using discord.py , i was trying delete the command when it is executed
it is working but giving me a error and the error is
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py",
line 312, in _run_event
await coro(*args, **kwargs)
File "C:/Users/Dell/Desktop/test_bot/add_role.py", line 25, in on_message
msg = await message.channel.fetch_message(761275239346339871)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py",
line 956, in fetch_message
data = await self._state.http.get_message(channel.id, id)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py",
line 243, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
After giving the error also it works , but i want to know what rises the error
code :
msg = await message.channel.fetch_message(761275239346339871)
await msg.delete()
The problem is, The message id that you inputted has already been deleted. If you want to delete the author message just do
await ctx.message.delete()
if you want to delete the inputted message by wait_for you can do this
msg = await client.wait_for('message', check=lambda message: message.author == ctx.author)
await msg.delete()
if on_message.
#client.event
async def on_message(message):
message = await message.channel.send(message here)
await message.delete()
import discord
import logging
from discord.utils import get
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#bot.command(pass_context=True)
async def setrole(ctx, a: str):
member = ctx.message.author
role = discord.utils.get(member.guild.roles, name=a)
await member.add_roles(member, role)
This is the code i use trying to assign roles to people entering the command. The role available in my server is rs6 so the code should be !setrole rs6 but its not working.
Ignoring exception in command setrole:
Traceback (most recent call last):
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Workshop\example_bot.py", line 19, in setrole
await member.add_roles(member, role)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\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: NotFound: 404 Not Found (error code: 10011): Unknown Role
I tried to do print(role) after line role = discord.utils.get(member.guild.roles, name=a)
and it printed rs6 which is correct. Someone please help me! Thanks!
You can do a snazzy thing using command decorators. In the same way that you've set the type of arg to be a str, you can also set it to be a discord object:
#bot.command() # Note that context is automatically passed in rewrite
async def setrole(ctx, role: discord.Role):
await ctx.author.add_roles(role)
await ctx.send(f"I gave you {role.mention}!")
You might want an error handler to deal with if the role isn't found:
#setrole.error
async def _role_error(ctx, error):
if isinstance(error, commands.errors.BadArgument):
await ctx.send("I couldn't find that role!")
References:
commands.BadArgument
Member.add_roles()
Error handler per command