Discord.py ticket system - python

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.

Related

Making a bot that can add multiple roles to a user at once

Basically I'm using nextcord, a fork of discord.py. I'm kind of new to programming in general, but since I like or have been on discord for some time and want to pursue a career requiring programming I said doing a small project such as this would be a good start.
import asyncio
import nextcord
from nextcord.ext import commands
from nextcord.ext.commands import guild_only
#client.command()
#commands.has_role("Admin")
async def giverole(ctx, member : nextcord.Member, role : nextcord.Role):
if role in member.roles:
await member.add_roles(role, atomic = True)
embed8a = nextcord.Embed(description = f"Removed **{role}** from **{member}**", color = nextcord.Color.orange())
await ctx.send(embed = embed8a)
else:
await member.add_roles(role, atomic = True)
embed7a = nextcord.Embed(description = f"Added **{role}** to **{member}**", color = nextcord.Color.orange())
await ctx.send(embed = embed7a)
Anyways, my issue is that in the code below I am able to add one role to a user at a time, however not multiple. According to the nextcord/discord.py documentation, using the "Atomic = true" attribute should make this possible but I've gotten several errors. I've listed the most current one below.
Traceback (most recent call last): File "C:\Users\De'shon\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ext\commands\bot.py", line 1381, in invoke await ctx.command.invoke(ctx) File "C:\Users\De'shon\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ext\commands\core.py", line 948, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\De'shon\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped raise CommandInvokeError(exc) from exc nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'id'

Key error in py-cord when using aiosqlite

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."

My Discord bot won't send embeds from within a cog. (AttributeError: 'int' object has no attribute 'send')

So basically I'm trying to put the commands of my Discord bot into cogs. It loads the cog just fine. But when I run the command and the bot tries to send an embed to my logging channel it doesn't work.
Here is the code:
from discord.ext import commands
import datetime
from ruamel.yaml import YAML
yaml = YAML()
with open(r"C:\Users\Jea\Desktop\Yuna-Discord-Bot\config.yml", "r", encoding="utf-8") as file:
config = yaml.load(file)
bot = commands.Bot(command_prefix=config['Prefix'])
bot.debugchannel = config['Debug Channel ID']
bot.embed_color = discord.Color.from_rgb(
config['Embed Settings']['Color']['r'],
config['Embed Settings']['Color']['g'],
config['Embed Settings']['Color']['b'])
bot.footer = config['Embed Settings']['Footer']['Text']
bot.footerimg = config['Embed Settings']['Footer']['Icon URL']
class Testing(commands.Cog):
def __init__(self, bot):
self.bot = bot
#bot.command(name="ping",
aliases=["p"],
help="Check if the bot is online with a simple command")
async def ping(self, ctx):
embed = discord.Embed(title=f"Pinged {bot.user}", color=bot.embed_color, timestamp=datetime.datetime.now(datetime.timezone.utc))
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=bot.footer, icon_url=bot.footerimg)
await bot.debugchannel.send(embed=embed)
print("Sent and embed")
await ctx.message.add_reaction('✅')
print("Added a reaction to a message")
await ctx.send("Pong!")
print("Sent a message")
def setup(bot):
bot.add_cog(Testing(bot))
print("Loaded testing cog")
This is the error it gives:
Traceback (most recent call last):
File "C:\Users\Jea\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\Jea\Desktop\Yuna-Discord-Bot\cogs\testing.py", line 34, in ping
await bot.debugchannel.send(embed=embed)
AttributeError: 'int' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jea\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\Jea\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\Jea\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: AttributeError: 'int' object has no attribute 'send'
and I know it is the line await bot.debugchannel.send(embed=embed). Because when I removed it, the command worked just fine. however, I don't know what is causing it. any help would be appreciated!
bot.debugchannel just stores the id of the channel, not a discord.TextChannel object, and it therefore cannot be used to send messages. First, you need to get the channel itself from the id, which can be done using ctx.guild.get_channel(<id>)
So replace line 4 of the ping method with the following two lines:
debugchannel = ctx.guild.get_channel(bot.debugchannel)
await debugchannel.send(embed=embed)
You might also want to consider changing the variable name of bot.debugchannel to bot.debugchannel_id or the like, to make it clearer what is going on here.

discord python bot kick command

i am trying to make a discord bot that can kick people with the command .kick
I have it display a message that says (username) has been kicked from the server and the message still shows up, but it doesn't actually kick them.
Here is my code:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
#client.event
async def on_ready():
print("Bot is Ready")
#client.command(aliases=['c'])
#commands.has_permissions(manage_messages = True)
async def clear(ctx,amount=2):
await ctx.channel.purge(limit = amount)
#client.command(aliases=['k'])
#commands.has_permissions(kick_members = True)
async def kick(ctx,member : discord.Member,*,reason= "I do not need a reason"):
await ctx.send(member.name + " has been kicked from the server, because "+reason)
await member.kick(reason=reason)
#client.command(aliases=['b'])
#commands.has_permissions(ban_members = True)
async def ban(ctx,member : discord.Member,*,reason= "I do not need a reason"):
await ctx.send(member.name + " has been banned from the server, because"+reason)
await member.ban(reason=reason)
the error message says:
File "C:\Users\user\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\user\discordbot\bot.py", line 18, in kick
await member.kick(reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 512, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\guild.py", line 1849, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
please note that my .clear command is working perfectly fine, it is just kick and ban
please help, I am on python 3.9.0
#client.command()
#commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member):
await member.kick()
await ctx.message.add_reaction("reaction")
await ctx.send(f"{member.name} has been kicked by {ctx.author.name}!")
await log_channel.send(f"{ctx.author.name} has kicked {member.display_name}")
This is what I used for my discord bot. It only lets the people with the kick permission use this command. I hope this helped.
This type of error comes when either user who is giving this command or your bot has not been given such admin permissions. In your server you can simply make one role for your bot or can give all privileges to your bot if it is managed by you.
link below may help you regarding this
https://support.discord.com/hc/en-us/articles/206029707-How-do-I-set-up-Permissions-

discord.py how to assign roles to users v1.0 version

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

Categories