#discord-bots
1 messages ยท Page 202 of 1
Does this sort of make sense? I know it looks a bit confusing
I can break it down so it's not a list comp
my_2d_list = [["row 1 col 1", "row 1 col 2"], ["row 2 col 1", "row 2 col 2"]]
display = ""
for row in my_2d_list:
display += " ".join(row) # joins the contents of ONE row with a space
display += "\n" # Add a line break
Pretty much does the same thing
No. You just adapt it easily into whatever display format you want
The logic is the same, however
How can I send the embed message only once for all the banned members?
# Check if the maximum number of new members has been exceeded
await asyncio.sleep(5)
if new_members_count > max_new_members:
# Ban all members in the list of new members
for member in new_members_list:
await member.ban(reason="Exceeded maximum number of new members in allowed time period.")
# Send an embedded message to the specified channel
channel = client.get_channel(745832392404762695)
discord.Embed(description=f'Server Raided:\n\nRaid Size: **{len(new_members_list)} accounts**', timestamp=datetime.datetime.now(), color=discord.Color.red())
embed.set_author(name="Anti Raid Detected", icon_url=avatar_url)
await channel.send(embed=embed)```
@smoky sinew @sick birch do i remove the return grid_str
it should only send one unless you have a loop before that
bc if i do the embed just says none
def predict():
mine_locations = get_mine_locations()
grid = get_safe_spots(mine_locations)
grid_str = ""
for row in grid:
grid_str += " ".join(row)
grid_str += "\n"
return grid_str
is this right loll
it still only shows 1 line
or am i just dumb
what should i do
you're still returning inside the loop
i wasn't talking to you
that's why i replied to beerhunter
Send a pic of how it looks like?
Oh, you have to return grid_str after the loop is completely done
Right now it just returns on the first loop iteration
!e ```py
my_2d_list = [["row 1 col 1", "row 1 col 2"], ["row 2 col 1", "row 2 col 2"]]
print(*(" ".join(row) for row in my_2d_list), sep="\n")
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | row 1 col 1 row 1 col 2
002 | row 2 col 1 row 2 col 2
wait so what do i do
then
i'll one up you
!e
a=[["row 1 col 1","row 1 col 2"],["row 2 col 1","row 2 col 2"]];print(*(" ".join(row)for row in a),sep="\n")
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | row 1 col 1 row 1 col 2
002 | row 2 col 1 row 2 col 2
help
I did
Anyone in here who can help me proper setup my pool connection for postgresql & asyncpg using a setup_hook?
what;s the issue
is there a command listener for commands that are only in a single cog?
!d discord.ext.commands.Cog.cog_before_invoke
await cog_before_invoke(ctx)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that acts as a cog local pre-invoke hook.
This is similar to [`Command.before_invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.before_invoke "discord.ext.commands.Command.before_invoke").
This **must** be a coroutine.
is this an inherited method
sure, its just a method you override in the cog
my bot is online, but won't ping zzz
it says it still says [2023-02-24 18:46:50] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected. even though they are all turned on
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.presences = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.event
async def on_message(message):
if message.content == 'hi':
await message.channel.send('hello')
await bot.process_commands(message)
bot.run('token')```
bot it online in server, has admin
I don't see you enabling message_content intent anywhere in that code
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.presences = True
intents.messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.event
async def on_message(message):
if message.content == 'hi':
await message.channel.send('hello')
await bot.process_commands(message)
bot.run('token')```
same error
message_content not messages
message.content = True ?
Enable it
has been enabled
that's kind of what I asked, it's just incorrect spelling
holy shit
I love you ๐

Can i edit an embed after its sent? Like change the color depending on the status etc
yessss
Hello, how do I fix this error?
for first you need to show code ๐
can I send it to you in pm?
yes
I sent you my code
you need to respond to the interaction within 3 seconds
yes possible, how can I fix it?
defer the response initially (inter.response.defer()), and then use folloup webhook to send the message( inter.followup.send(...))
what is the followup webhook?
@slate swan
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
basically the webhook used to create slash responses
I have a little question please, how can I make it that the user can either mention someone in a slash commands, and it optional
@app_commands.command(name="berries", description="to know how much Berries you got")
@app_commands.describe(user="if you want to check the berries of someone else you can mention them")
async def cardinfo(self, interaction: discord.Interaction, user: discord.member=None):
# Connect to the database
if user== None:
user_id= interaction.user.id
else:
user_id= interaction.user.mention.id```
I am trying this
but the error is that interaction.user.mention got no attribut id
Can someone help me with my code
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
'X-Auth-Token': auth_token
}
params = {'size': '2', 'page': '0'}
def get_mine_locations():
response = requests.get('https://rest-bf.blox.land/games/mines/history', headers=headers, params=params)
data = json.loads(response.text)
return [location for game in data['data'] for location in game['mineLocations']]
import requests
import random
def get_safe_spots(mine_locations):
# Create a set of all safe spots
all_spots = set(range(25))
mine_spots = set(mine_locations)
safe_spots = all_spots - mine_spots
# Choose 5 random safe spots
safe_spots_list = list(safe_spots)
random_safe_spots = random.sample(safe_spots_list, 5)
# Sort the mine locations by row then column
sorted_mine_locations = sorted(mine_locations, key=lambda loc: (loc // 5, loc % 5))
# Create the grid with emojis
grid = []
for i in range(5):
row = []
for j in range(5):
index = i * 5 + j
if index in random_safe_spots:
row.append('๐ฃ')
elif index in mine_locations:
row.append('โ')
else:
row.append('โญ')
grid.append(row)
return grid
def predict():
mine_locations = get_mine_locations()
grid = get_safe_spots(mine_locations)
grid_str = ""
for row in grid:
return grid
predict()
@bot.slash_command(name="minesplay_bomb")
@commands.has_role("Buyer")
async def bloxflip(ctx):
raid = predict()
embed = discord.Embed(title="**Radiant Predictor**", description=f"{raid}")
await ctx.respond(embed=embed)```
when i run it and use the command it looks like this:
i want it to be a 5x5 grid
Use /n
With a for loop with range
Just use join
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('siam'):
await message.channel.send('Hi there!')```
bot is not sending any msg
it has admin
Did u enable message intents?
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
Oh great!
idts many people would actually use a chatbot anymore
we need a bot that teaches people real social interaction skill
no a fun chatbot like chill, cleverbot lol
Make it tell them try to interact with actual people
nvm I won't make a comment anymore
@tree.command(name="object", description="Randomly uploads a picture from a specific directory.")
async def object(int: discord.Interaction):
directory_path = "/path/to/directory" # replace with the path to your directory of images
image_files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f)) and f.endswith(".jpg")] # replace ".jpg" with the file extension of your images
if len(image_files) == 0:
await int.response.send_message("No images found in directory.")
return
selected_image = random.choice(image_files)
with open(os.path.join(directory_path, selected_image), "rb") as f:
file = discord.File(f)
await int.response.send_file(file, content=f"Here's a picture: {selected_image}")
btw guys what's wrong here
not a great idea to name the arg int...
depends on the error
error is "has no attribute send_file"
so what do i do
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
that's the complete error lol
No it's not
@quick gust
The screenshot crops out main parts of the error... Please copy paste the entire thing
2023-02-24 20:51:22 ERROR discord.app_commands.tree Ignoring exception in command 'object'
Traceback (most recent call last):
File "C:\Users\SALMAN\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 862, in has no attribute 'send'
how do i start a loop that is inside a cog
everythig works fine and the cog gets loaded
the loop just doesnt start
u should delete discord.py and download nextcord
it's the same thing but better
discord has a lot of errors
same thing but getting updated, nextcord can get any errors dpy also gets lol
I think it is send_message
code
async def on_submit(interaction: discord.Interaction):
await interaction.response.send_message(f"New password set!")
if result is None:
sql = ("INSERT INTO pass(user_id, platform, acc_name, pass_name) VALUES(?, ?, ?, ?)")
val = (interaction.user.id, plat, acc, pas)
elif result is not None:
sql = ("UPDATE pas SET plat = ?, acc_name = ?, pass_name = ? WHERE user_id = ?")
val = (plat, acc, pas, interaction.user.id)
await cursor.execute(sql, val)
await db.commit()
async def button_callback(interaction: discord.Interaction):
create_account = Modal(title="Password setup")
create_account.on_submit = on_submit
create_account.add_item(plat)
create_account.add_item(acc)
create_account.add_item(pas)
await interaction.response.send_modal(create_account)```
error
```line 81, in on_submit
await cursor.execute(sql, val)```
pls help
What's the error bro
you see under the code the "error" thing
i also got this "sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type."
This is the error
can anyone here tell me how to start a loop inside a cog rq, i have my whole loop, the cog gets loaded but it doesnt start, do i have to put a start function somewhere ?
you need to use
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2.0.
the cogs are being loaded
as i have already said in my message
the loop just doesnt start
hi willi
cog_load gets called when the cog is loaded
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_load(self): # Doesn't matter if it's an async function if you're not doing async stuff in it
# start your loop here
Should work.
so u want me to put my loop in there
or just some loop.start
.start
kk i will
That's not very nice @desert badger
that's dumb
why would you force a certain library on someone
discord.py doesn't have a InteractionResponse.send_file method, so it's not needed to see the error beyond what they sent
that's not forcing
"u should delete discord.py"
it's a discord bot development channel, you should be able to get help no matter what library you use
id consider "should" as a suggestion, though i would like to hear details on discord.py having lots of errors
I saw this while I was looking for help in github and it actually changed my mind on using discord.py, so if you want you can read it.
||https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1||
Note: This is not an ad
after all it was just an advice not "Force".
that was a long time ago
just peeking at the discord.py commit history should let you know that it obviously wasn't dropped
you should see the gist danny created six months after that
https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
dpy 2.0 was released (coincidentally also) six months ago, and the most recent version, 2.1.1 came out just a couple weeks ago
Is there a way to check what messages I'm sending to a user just from the dm?
How do you clear the users list users = [] if it's a global variable?
!e
users = ["Alice", "Bob", "Charlie"]
def clear_users():
global users
users = []
print(users)
clear_users()```
@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.
[]
!d list.clear
!e
a = list(range(10))
def func():
a.clear()
print(a)
print(a)
func()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
002 | []
Thanks
that's very outdated
does anyone know how to make a transcript cmd for tickets
yes
loop over all the messages in the ticket and write them to a text file
alr
i've got a ticket command, i want to make it so you can only create one ticket at a time and if you have one open it sends an ephemeral message and it doesn't create a channel but if you don't have one it creates it. if anyone could help, that'd be great, this is my cuurrent code
@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def _order(interaction, title:str):
guild = interaction.guild
category = discord.utils.get(guild.categories, name="Tickets")
if category is None:
await guild.create_category_channel(name="Tickets")
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
orderEmbed.add_field(name=f'{title}', value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
orderEmbed.set_footer(text="Corpotics")
await channel.send("<@&1078464006433542154>", embed=orderEmbed)```
Before creating the text channel, check if a channel with the name "ticket-user-0000" exists ๐คท
Also, might want to assign category to what create_category_channel returns
if category is None:
await guild.create_category_channel(name="Tickets")
would this work?
if not interaction.channel.name.startswith(f'ticket-{interaction.user}'):
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
return
await interaction.response.send_message("You already have ticket open!", ephemeral=True)
That doesn't check whether a channel already exists. You're returning early too, so the send_message will never be executed.
what about this?
if channel.name == f'ticket-{interaction.user}':
await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
Check if the name of any channel in the "Tickets" category matches what you have. Do note that text channels can't have special characters, and interaction.user includes a #
Anyone that can help me?
This is what I keep getting in my console:
list index out of range
Every time someone types in a server where my bot is in, I assume it's connected to my database, but the only 3 things with database code in it, are my prefix command. my afk command and the way my bot gets the prefix, which is this:
async def prefix(bot, message):
data = await bot.db.fetchval('SELECT prefix FROM prefix WHERE guild_id = $1', message.guild.id)
if data:
return commands.when_mentioned_or(data[0])(bot, message)
else:
return commands.when_mentioned_or(',')(bot, message)
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
There is no "traceback"
Or else I would've included it. this is all i'm getting in my console.
Then I can't tell where exactly the error came from
how would i include the #?
You want to exclude it
There should, otherwise you wouldn't've gotten "list index out of range." Perhaps you've got an error handler that's eating your errors
how?
I would say keep the discrim part otherwise, it'll error with common usernames
ok turns out it's my afk event handler, but the weird part is that it does get the data from the database table&row, just doesnt send the thing that it needs to send.
But it still doesn't give me the error of what the problem is
@commands.Cog.listener()
async def on_message(self, message):
ctx = await self.bot.get_context(message)
if message.author.bot: return
data = await self.bot.db.fetch('SELECT * FROM afk WHERE user_id = $1', message.author.id,)
if data:
print(data)
timestamp = data[0][2]
time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
await self.bot.db.execute('DELETE FROM afk WHERE user_id = $1', message.author.id,)
await ctx.success(f'Welcome back, you were away for **{time}**')
if message.mentions:
for mention in message.mentions:
data = await self.bot.db.fetch('SELECT * FROM afk WHERE user_id = $1', mention.id,)
if data and mention.id != message.author.id:
print(data)
timestamp = data[0][2]
time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
await ctx.success(f'**{mention}** is currently **AFK**: {data[0][1]} - {time} ago')
This is my afk event handler
nvm, it already excludes
But it's not sending the welcome back message if the person who is in the afk database types or when they get mentioned
Which makes 0 sense to me
if channel.name == f'ticket-{interaction.user}':
await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
it continues to make a ticket even if i have a ticket open
Send the full code
@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def _order(interaction, title:str):
guild = interaction.guild
category = discord.utils.get(guild.categories, name="Tickets")
if category is None:
await guild.create_category_channel(name="Tickets")
channel = discord.utils.get(guild.channels)
if channel.name == f'ticket-{interaction.user}':
await ctx.send(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
orderEmbed.add_field(name=f'{title}', value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
orderEmbed.set_footer(text="Corpotics")
await channel.send("<@&1078464006433542154>", embed=orderEmbed)```
this code creates the ticket but it doesn't check if they already have a ticket open. it creates the channel even if htey have one open, no errors. can someone help?
that's not how you use discord.utils.get
would this owrk?
guild = discord.utils.get(bot.guild.categories, id='1078823637609631765')```
Hi, I'm making a rob command where the user has some chances to win (they can use power ups to increase the chances) and the target user also has some defence chances (which they can increase). I need a true/false value to check if the user won or not. Can anyone suggest a good method to do it? Sorry for my English :)
!e
import random
for _ in range(10):
n = random.randint(1, 2)
print(n, n == 1)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2 False
002 | 1 True
003 | 2 False
004 | 1 True
005 | 2 False
006 | 2 False
007 | 2 False
008 | 2 False
009 | 2 False
010 | 1 True
50/50 ๐ฅค
!d random.random
random.random()```
Return the next random floating point number in the range `0.0 <= X < 1.0`
!e
import random
n = random.random()
print(n, n >= 0.5)
n = random.random() + 0.1 # increases the chance by 10% or whatever it's called
print(n, n >= 0.5)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0.48633593873984005 False
002 | 1.0745200817226221 True
no, ids are not strings
pretty sure you can just use guild = bot.get_channel(id)
would that fix the code?
U can do
guild.get_channel too tho i prefer it most xd
Anyone that knows humanize properly?
For some odd reason this line in my afk event handler broke: ```time = humanize.precisedelta(timestamp - discord.utils.utcnow().timestamp(), format='%0.f')
and i've got no clue on why
^
why don't you try it and see
would it be category = bot.get_channel(1078823637609631765) because if i leave it as guild = bot.get_channel(1078823637609631765) category would be undefined
are you intentionally doing timestamp - discord.utils.utcnow()...?
Yes I am, but its already fixed, thanks anyway!
great
it would be category yeah
ok
it doesn't work
just c\reates the tickets still
even if i have one open
i don't get what you are asking, you want to get the text channel with the id
no
the reason is discord.utils.get with one parameter will just return the first text channel it sees
yes you do, because how else will you check if the user has already opened a channel
cant i do it by the name?
how would i?
@bot.tree.command(name="order", description="Creates a ticket to order a bot.")
async def order(interaction):
guild = interaction.guild
category = bot.get_channel(1078823637609631765)
if category is None:
await guild.create_category_channel(name="Tickets")
channel = discord.utils.get(guild.channels)
if channel.name == f'ticket-{interaction.user}':
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)
await interaction.response.send_message(f'Your ticket has been created. {channel.mention}', ephemeral=True)
orderEmbed=discord.Embed(title="New ticket!", color=0x23B425)
orderEmbed.add_field(name="", value=f'Thanks for creating a ticket {interaction.user.mention}, please wait for one of our staff members to assist you!', inline=False)
orderEmbed.set_footer(text="Corpotics")
await channel.send("<@&1078464006433542154>", embed=orderEmbed)```
this is the current code
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
would the name be the name of the category
no, you are looking for the user's ticket channel
discord.utils.get(list, attribute=value) just returns an item inside list that has an attribute equal to value
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s...
there are examples in the docs as well ^^
channel = discord.utils.get(guild.channels)
no
did you see this
im confused
@commands.command(
name='kick',
usage='kick (user) <reason>',
description='void#0480 calm down',
aliases=['boot'])
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, user: discord.Member, *, reason: str = 'No reason provided'):
"""Kick a user from the server"""
if user is ctx.author:
return await ctx.success('You\'re unable to **kick** yourself')
if user is ctx.guild.owner:
return await ctx.success('You\'re unable to kick the **guild owner**')
if user.top_role >= ctx.author.top_role:
return await ctx.success('You\'re unable to kick a user with **superior roles** than you')
if user.top_role >= ctx.guild.me.top_role:
return await ctx.success('You\'re unable to kick a user with **superior roles** than me')
else:
await user.kick(reason=f"{str(ctx.author)} ({ctx.author.id}) | {reason}")
await ctx.reply('๐๐พ')
How do I make it so the server owner can ALWAYS ban someone with the same role as them and if the bot is below the server owners role
i'm not sure what you're saying, the bot can only ban people with lower roles
Well yes either that and it also cant ban people with the same role
but for instance, server owners, they normally can ban anyone even tho they have the same role
so what's the issue? the bot is already able to ban people below it isn't it?
But i'm trying to make it that it can bot can ban/kick someone with the same role as the owner if the command is issued by the owner
@smoky sinew im trying to make it so if you use /order and you already have a ticket open, it sends an ephemeral message. if you dont have one open, it will open a ticket. im trying to make it detect whether they have a ticket open by the name
i know, i already told you how to do it with utils.get but i will say it again
channel = discord.utils.get(category.channels, name = "channel name")
if channel:
# error
else:
# create the channel
Why don't just use ban button at that point
Because that's not what I'm trying to do
I'm trying to code it into the bot, not use the button
Using the button is way too much effort mate
if (
user.top_role >= ctx.author.top_role
and ctx.author != ctx.guild.owner
):
return await ctx.success('You\'re unable to kick a user with **superior roles** than you')
?
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}')
if channel.name == f'ticket-{interaction.user}':
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
what's even the point of having the return statements? @vital glacier
you already have the channel name why would you make an if statement
if it can't find a channel with name utils.get will just return none
The return statements are there because it'll spam ever single embed if they're not there
so just use elif
genuinely i keep forgetting that that's a thing
also you're going to get an error with that if the channel does not exist
lol no worries
but that wont check if they have a ticket already
and if the channel doesn't exist, shouldnt it make the channel?
yes it would, if the channel doesn't exist then the ticket hasn't been created
this works fine
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}')
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}'
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)```
?
Yes
if channel means it didn't return None
and else means it did return None
!e
a = None
if a:
print("it's not None!")
else:
print("it's None")
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
it's None
!e
a = 2234
if a:
print("it's not None!")
else:
print("it's None")
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
it's not None!
so ```py
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}')
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}')
else:
channel = await guild.create_text_channel(f'ticket-{interaction.user}', category=category)``` should work?
Kinda simple
Yes it will work
Also, suggesting to send the error message with ephemeral True
oh yeah, iwas gona do that

Tho sometime it may not work because of bad symbols on name
Try with
interaction.user.id for test
To check if thr code is working or not
Yep
Oh also, if they changes the name, they can no longer create ticket 
Or access it
Discriminator would be good too, but sometimes the discriminator is same, but maybe you can use channel's description, and set the description to user id
So check it now?
yeah it works
Nice
U can use this too
if its id and they cahnged their name, theyd still be able to access it, right?
Some of ticket bots use this method
Yep
I mean for good looking, you can use the user name on ticket and set the description to the id
Lemme check the docs tho ๐
but if i did that and they cahnged their name, wouldnt they not be able to access it?
Hmm
But u can compare their id by the channel's description id
how would i do that
if ....id==channel.somedescriptionattr.id:
# do work
Need to check docs xd, gimme a couple of seconds
ok
!d discord.TextChannel.topic
The channelโs topic. None if it doesnโt exist.
mhm
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user}', topic=f'This ticket is for {interaction.user.id}!')```
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a โsecretโ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
No need of name=...
isnt name the title of the channel?
Only topic
You just set the topic and compare it
Check up of the image, the texts in small sizes are topic
"For questions ....."
mhm
So u can just set the channel topic on
create_text_channels
Btw this all stuff is for making the ticket channel name good 
Giving id as ticket channel name looks ugly
yeah ikr
channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')```
so like,
channel = discord.utils.get(category.channels, topic=str(interaction.user.id))
if channel:
#send err msg
else:
create_text_channel(name=...., topic=str(interaction.user.id))
Yes
The topic SHOULD BE the same while creating the channel
wait so what will the name be
channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(topic=f'This ticket is for {interaction.user.id}!', category=category)```
Give the name as the user name
Using topic, now the name doesn't matter that much
just do,
name=interaction.user.name
channel = discord.utils.get(category.channels, name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!')
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!', category=category)```
Add
global count, top of the function
Remove the name=... From
utils.get()
No sec
Fk keyboard
channel = discord.utils.get(category.channels, topic=f'This ticket is for {interaction.user.id}!')
if channel:
await interaction.response.send_message(f'You already have an open ticket! {channel.mention}', ephemeral=True)
else:
channel = await guild.create_text_channel(name=f'ticket-{interaction.user.name}', topic=f'This ticket is for {interaction.user.id}!', category=category)```
@bot.event
async def on_message(message):
global count
global bot.chat
Yes!
Yes
bro ur actually the best tahnk u so much
Now there will be no e4ror
:)
by any chance, do you know how to make transcripts?
Ah, remove the
global bot.chat then lol
Yeah you can, i forgor it, gotta check docs lmao
Yeah i forgor
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destinationโs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
Here,
There is an example too
is limit for however much messages the transcript will get?
ok
What the ๐๐
am i able to make it so the transcript is sent to dms and a logging channel when /close deletes the channel?
Yep u can
can u give me an example?
Just wait some 5 secs, then generate all messages in a txt file with the history() method and send that ti the dm
channel=interaction.channel
message=""
async for messages in channel.history(....):
message+=messages+"\n"
await interaction.user.send(message)
Pretty simple
Just name it
chat={}
It isn't the best way
the messages is a discord.Message object i forgot xd
how would u make it so it only sends it to the dm of the person who created the ticket not the person who used /close
This is where, the topic will come in handy,
Tho that's why i told you to do
topic=str(interaction.user.id)
So it will be easy to retrieve the id easily
This isn't good but try
so rather than topic=f'This ticket is for {interaction.user.id}! ill make it topic=str(interaction.user.id)?
Wait for someone to help fr xd
Yea
ok
Then u can do,
member=guild.get_member(int(channel.topic))
await member.send(...)
where do i do that?
oh nvm
channel=interaction.channel
message=""
async for messages in channel.history(....):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
await member.send(...)```
so then how would i make it so it sends when the ticket is closed
Btw, correct it please...
message+=f"{messages.author.name}: {messages.content}\n"
Just use
/close
then do the stuffs
then
channel.delete()
Simple...
What error?
correct which line?
message+=messages+"\n"
ok
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
channel=interaction.channel
message=""
async for messages in channel.history(....):
message+=f"{messages.author.name}: {messages.content}\n"
await interaction.user.send(message)```
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I'm stuck with my inrole command, this is what i've got right now and i'm not completely sure how it works. I've got no errors either.
name='inrole',
aliases=['members'],
usage='inrole',
description=''
)
async def inrole(self, ctx, role: discord.Role = None):
"""View the users in a role"""
await ctx.typing()
embeds = []
ret = []
num = 0
pagenum = 1
for m in ctx.guild.members:
if role in m:
num += 1
ret.append(f'**{num}.** {m.mention} ({m.id})')
pages = [p for p in discord.utils.as_chunks(ret, 10)]
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
description="\n".join(page))
)
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji='')
pag.add_button('next', emoji='')
pag.add_button('goto', emoji='')
pag.add_button('delete', emoji='')
return await pag.start()```
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
await interaction.channel.delete()
channel=interaction.channel
message=""
async for messages in channel.history():
message+=f"{messages.author.name}: {messages.content}\n"
await interaction.user.send(message)``` @shrewd fjord is this right
Add delete line below the code
ok
Also make sure to do
@app_commands.checks.has_permissions(manage or whatever perms)
So that only specified people can delete it
Or just check it on the code
So that the ticket author can close it too
What error u r getting tho?
Oh wait
It will spam the dm
it will be
async for .........:
.....
await member.send(....)
You added member.send method inside the loop ๐
Ugh this shouldn't be happening ๐
what do i put for .........
the same code
Just
indent the member.send
async for....:
...
await send()
it was
async for.....:
...
await send()
ohh
And thus it spammed the dm
Sorry, tankman, I can't help with that error, seems like some internal problem, because the error wasn't supposed to occur
it sends whatever message was sent first in the ticket channel at the bottom and whatever was sent last at the top, is there a way to invert it?
@shrewd fjord
oldest_first=True
pip install -U discord.py
ohh
awesome thanks
is there a way to send all the messages all in one of these things:
like
this```
because currently they're all seperaate\
Yes it's possible
Show the current code
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True):
message+=f"```{messages.author.name}: {messages.content}\n```"
await interaction.user.send(message)
await interaction.channel.delete()```
await interaction.user.send(f"```{message}```)
-_-
yeah just did
Nice
Sure hold on
Also make sure to give
limit=something bigger as because it's default to 100 only
ok
Postgres ๐ฟ
thank you so much
how do i make it so it says who clsoed the ticket, would it be {interaction.user}
Yeah
Ticket closed by {interaction.user}
Str not needed actually xd
Bro fr, when i was just a beginner, struggled so much to get transcripts cmd to work ๐๐ and ended up giving up lmfao
๐ฟ๐ฟ๐ฟ๐ฟ
@vale wing handle his problem dude ๐ฟ
It isn't impossible, cause i already made a discord chat bot with open ai
๐ญ
So there is no way to giving this up
Whose problem
Tankman
What problem
Bro the
bot=....
Says unboundlocalerror like fr? ๐๐
Hmm 
@shrewd fjord i just realised
The answer is "nowhere"
it sends the transcript to the eperson who closed the ticket
Eh wait
Use
member=guild.get_member(int(channel.topic))
await member.send()
Why do you redefine bot
I hope, you changed the channel.topic to that format i said
Lines 92 & 102
He redefined?
the id?
Yeah they redefine bot for no reason
Bot only needs to be defined once
From the line 102
They need to remove almost whole except clauses
Ye
Because they basically copied code from the beginning into excepts
which line do i add member=guild.get_member(int(channel.topic))
He redefined the intents too
just do
member=....
await member.send(...)
instead of
await interaction.user.send(...)
Yeah
Remove the whole stuff from 98 to 102 something
Remove 87-94
And 97-104
This lines are useless and giving you error
Btw did you do
topic=str(interaction.user.id)
?
Or the above code won't work
Noice
everything works, now i just need to do which is easy. tysm @shrewd fjord
tbh i didint think i could make a ticket system
Btw you should handle the errors too
try:
await send(...)
except discord.HTTPException:
return #or whatever you want
its pretty basic but it has all the essentials
Yeah ๐ฟ
for what?
So u r trying to do
await None.send(...)
Will return error
NotFound
Also imagine his dm is close ๐
๐ญ
so send it under
try-except block
return await interaction.response.send_message("I couldn't dm you the transcript for unknown reasons", ephemeral=True) will be good
@shrewd fjord
it didnt send the error message after they lefgt
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
guild = interaction.guild
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
try:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except discord.HTTPException:
return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await interaction.channel.delete()```
error:
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 65, in close
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'```
Ohhh
Try...
remove try-except
And do,
if member:
#send member the message
else:
#send error message with return ....
if member:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
else:
return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")```?
Yeah
ok
I thought it will return NotFound
Still it's bad way to do ๐
You can catch up all error using
except:
But a bare exception is bad lol
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 65, in close
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} {message}')
AttributeError: 'NoneType' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
it didnt close the ticket either
Current code?
Because we returned it
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
guild = interaction.guild
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
if member:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
else:
return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await interaction.channel.delete()```
Oh wait lets defer it
Ughhh
It's a annoying fr ๐๐
Idk in which line the problem is
File "main.py", line 65, in close
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason}
{message}
')
Send the full traceback
ig do this for test:
try:
await member.send(...)
except Exception as e:
print(e)
await interaction.response.send_message(...)
This time will not return, and we will catch ALL the errors
^
And print it ofc
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
guild = interaction.guild
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
try:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except Exception as e:
print(e)
return await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await interaction.channel.delete()```
?
except Exception as e:
print(e)
await interaction.response.send_message(...)
await interaction.channel.delete()
!d discord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
except Exception as e:
print(e)
await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await interaction.channel.delete()
Yeah
it said I couldn't DM the transcript for unkown reasons! then it deleted
Yeah then it worked
ok
Check the console, the error maybe showed up
it didint
print(e)?
The error will be in white color xd
Not red ๐ฟ
Use asyncio library too, to make some delay on deleting the channel
yeah i did that before u said that lol
'NoneType' object has no attribute 'send'
Yeah
Tho i thought it will raise exception but nvm ig
Now u can remove
print(e) line and u r done
awesome, tysm
U should create a log channel btw, where u will store the errors
ok
ill make a ticket-logs channel where it will send who closed the ticket, the reason the transcript and error (if there is one)
Um actually, you should use database even if bot is not public ๐ค
a database for what
Yeah, but changing some code for one server only is faster imo
guys can anyone help me?
Just drop the ques
@shrewd fjord
@bot.tree.command(name="close", description="Closes the ticket!")
async def close(interaction, reason:str):
guild = interaction.guild
channel = bot.get_channel(1078949152735641650)
if not interaction.channel.name.startswith('ticket-'):
await interaction.response.send_message('This is not a ticket channel.', ephemeral=True)
return
channel=interaction.channel
message=""
async for messages in channel.history(oldest_first=True, limit=5000):
message+=f"{messages.author.name}: {messages.content}\n"
member=guild.get_member(int(channel.topic))
try:
await member.send(f'Your ticket was closed by {interaction.user.mention} for {reason} ```{message}```')
except Exception as e:
await interaction.response.send_message("I couldn't DM the transcript for unkown reasons!")
await asyncio.sleep(10)
await interaction.channel.delete()
ticketlogEmbed=discord.Embed(title="Ticket Closed", color=0xFF5349)
ticketlogEmbed.add_field(name="Opened by:", value=f'{member.mention}', inline=True)
ticketlogEmbed.add_field(name="Closed by:", value=f'{interaction.user.mention}', inline=True)
ticketlogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
ticketlogEmbed.set_footer(text="Made by justin;#6868")
ticketlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(f'```{message}```', embed=ticketlogEmbed)``` im trying to make it send to the ticket log channel but it doesnt send to the channel but everything else works
i got an error
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 78, in close
await channel.send(f'```{message}```', embed=ticketlogEmbed)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/abc.py", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/http.py", line 740, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/corpotics/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'close' raised an exception: NotFound: 404 Not Found (error code: 10003): Unknown Channel```
log_channel=guild.get_channel(id)
Then send it
await log_channel.send(f'{message}', embed=ticketlogEmbed)
Yeaa
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
@commands.command(
name='guilds',
usage='guilds',
description=''
)
async def guilds(self, ctx):
"""View the servers that the bot is in"""
await ctx.typing()
embeds = []
ret = []
num = 0
pagenum = 1
invite = await guild.text_channels[0].create_invite(max_age=0, max_uses=0, unique=True)
if self.bot.guilds is None:
return
for guild in self.bot.guilds:
num += 1
ret.append(f'**{num}.** {guild.name} ({guild.id}) - [Invite]({invite})')
pages = [p for p in discord.utils.as_chunks(ret, 10)]
for page in pages:
pagenum += 1
embeds.append(discord.Embed(
color=color,
description="\n".join(page))
)
pag = Paginator(self.bot, embeds, ctx, invoker=ctx.author.id)
pag.add_button('prev', emoji=':back:')
pag.add_button('goto', emoji=':enter:')
pag.add_button('next', emoji=':next:')
pag.add_button('delete', emoji=':stop:')
return await pag.start()
Any reason this wouldn't work?
nvm solved
!d help
help()``````py
help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.

There probably are russian programming communities but knowing english is very helpful
@bot.tree.command(name="collect",description="Collect from your stadium to upgrade your "
"hissatsus")
@app_commands.checks.cooldown(1, 86400.0, key=lambda i: (i.guild_id, i.user.id))
async def collect(interaction: discord.Interaction):
d2=conn.cursor()
member_id = interaction.user.id
try:
stad = d2.execute(
f"SELECT stadium FROM games WHERE member_id ={member_id}").fetchone()
if stad == 'Condor Stadium':
random_number = random.randint(1, 100)
elif stad == 'Kujaku Stadium':
random_number = random.randint(50, 150)
elif stad == 'Yamaneko Stadium':
random_number = random.randint(100, 200)
elif stad == 'Umihebi Stadium':
random_number = random.randint(150, 250)
elif stad == 'Titanic Stadium':
random_number = random.randint(200, 300)
elif stad == 'Football Stadium':
random_number = random.randint(250, 350)
elif stad == 'Cyclone Stadium':
random_number = random.randint(300, 400)
elif stad == 'Amano Mikado Stadium':
random_number = random.randint(350, 450)
elif stad == 'Desert Stadium':
random_number = random.randint(400, 500)
elif stad == 'Holy Road Stadium':
random_number = random.randint(450, 550)
d2.execute("""
UPDATE games
SET money = money + ?
WHERE member_id = ?
""", (random_number, member_id))
conn.commit()
await interaction.response.send_message(f"You have added {random_number} $ to "
f"your "
"profile")
except Exception:
await interaction.response.send_message('u on cooldown')
``` i have this code but it send u on cooldown as soon as one user use it but i want every user to be able to use it once a day
can somenone help me?

u have to store the cooldowns somewhere
Hey so... i have a code that my client just sent me and I'm not at home, can anyone test it for me and say if it works? Its a anti-spam system
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
# Define the spam threshold and the number of messages to check
SPAM_THRESHOLD = 5
SPAM_RATELIMIT_SECONDS = 5
# Define a dictionary to keep track of user spam counts
spam_counts = {}
@bot.event
async def on_message(message):
# Check if the message author is a bot
if message.author.bot:
return
# Check if the message is in a guild/server
if message.guild is None:
return
# Get the author ID of the message
author_id = message.author.id
# Check if the author ID is in the spam_counts dictionary
if author_id in spam_counts:
# Increment the user's spam count
spam_counts[author_id] += 1
# Check if the user has exceeded the spam threshold
if spam_counts[author_id] >= SPAM_THRESHOLD:
# Delete the user's messages in the last SPAM_RATELIMIT_SECONDS
async for past_message in message.channel.history(limit=SPAM_THRESHOLD):
if past_message.author.id == author_id and (message.created_at - past_message.created_at).seconds < SPAM_RATELIMIT_SECONDS:
await past_message.delete()
# Warn the user
await message.channel.send(f"{message.author.mention}, please refrain from spamming.")
# Reset the user's spam count
spam_counts[author_id] = 0
else:
# Add the author ID to the spam_counts dictionary with a spam count of 1
spam_counts[author_id] = 1
# Process the message normally
await bot.process_commands(message)
bot.run('token')
does anyone know how to solve this error? In allowed_mentions.replied_user: must be either true or false
I have this part of the code
view=ticket_options()
AllowedMentions = discord.AllowedMentions(everyone=False, users=False, roles=False, replied_user=False)
await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
!code and this
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
i would assume mention_author=interaction.message.author.mention is the issue, given that its meant to take a boolean

the traceback is in this line
await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)
Send the traceback
.
The whole traceback
why do you want to set both allowed_mentions.replied_user and mention_author at the same time?
File "", line 425, in _scheduled_task
await item.callback(interaction)
File "", line 117, in TicketMenu
await interaction.channel.send(embed=embed_question, allowed_mentions=AllowedMentions, mention_author=interaction.message.author.mention, view=view)
File "", line 1538, in send
data = await state.http.send_message(channel.id, params=params)
File "", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In allowed_mentions.replied_user: Must be either true or false.
they both mean the same thing, but mention_author takes precedence over replied_user, and the problem is that you've given some string to mention_author instead of the boolean that the discord API was expecting
ok it was it
what a dumb mistake
Hmmm I dont understand
the error raised gets passed to tree.on_error youll have to override it
!d discord.app_commands.CommandTree.on_error
await on_error(interaction, error, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
Whenever I ask here I feel more useless xD ik shit lmao
that's fine, you're learning! also your if statement flow can be shortened
instead of py if x == "a": num = ... if x == "b": num = ... some other things you can create a dictionary ```py
data = { "a": ..., "b": ... some other things}
num = data[x]
Or you can also use match case if on 3.10 ๐
I want to get the rocket league api for the in game stats like what rank is the ctx.author in 2v2. I have searched for it online but there was nothing about it. Is there an import that maybe can help me with this?
ohhhhhhhh
i didnt know
Hello can somone help me
!d client = commands.Bot(command_prefix="!")
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
hmmm but i have a question here
what would that help me with my problem?
not related to your problem, just a refactoring suggestion
oh xD
yeah that on_error thing answers your main question
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
hmmm but my problem is not with the error handlerer
so that means i got to go to discord dev portal and put on intents on my bot?
I am trying to add an "update" button to my embed responses, but for some reason I get: Unknown interaction
@discord.ui.button(label="Next", style=discord.ButtonStyle.green)
async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.pagenumber == (self.listlength - 1):
self.pagenumber = 0
else:
self.pagenumber = self.pagenumber + 1
embed = self.setembed(self.pagenumber)
await interaction.response.edit_message(embed=embed, view=self)
@discord.ui.button(label="Update", style=discord.ButtonStyle.green)
async def update_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.update(self.pagenumber)
embed = self.setembed(self.pagenumber)
await interaction.response.edit_message(embed=embed, view=self)
``` Snipped of my code.
Why am I getting an error? It's confusing to me ;-;
You can use InteractionResponse only once
But the previous/next buttons work as intended tho
Eh, I probably misread something
What's self.update
And can you send the full traceback
A function I run to update the data I have that then gets passed to the embed and suppose to update
1 sec
i would just like to know to make you select a discord user like this, im learning app_commands and im trying to make an avatar command
Traceback (most recent call last):
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Declan\Desktop\discordbots2\adminmaster\cogs\alts.py", line 324, in update_button
await interaction.response.edit_message(embed=embed, view=self)
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 874, in edit_message
await adapter.create_interaction_response(
File "C:\Users\Declan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
@app_commands.command(name="hello", description="Says hello")
async def hello_command(self, interaction: discord.Interaction, member:discord.Member):
await interaction.response.send_message(f"Hello {member.mention}")
you can then do /hello @drifting arrow
output:
Hello @drifting arrow
Set the argument's typehint to discord.User or discord.Member, and discord.py will do the job
Unfortunately that's not the case ๐ฆ
Did you try
I am able to actively and freely use the previous/next buttons but once I try and do Update it errors. so i know it's not a timeout issue
man I tried to use discord_slash before, i tried updating, uninstalling it and reinstalling it again
but it doesnt work 
why you're using such a thing
discord.py supports slash commands
Make sure you're using the latest version of discordpy
and have from discord import app_commands
yeah
somone help meeee
Can anyone explain me these thinks like
"Import ..."
Because i dont know what it does
no.
it imports a library
delete the parenthesis after command_prefix
omg ty bro let me see if it works
and add a comma
also make sure to add a ,
client = command.Bot(command_prefix="!", intents=intents)

like this?
also it gives me an error lol
@rose thistle
nope
probably. idk. i didnt test.
commands
Whats your error
also do intents=discord.Intents.all()
he is prob running it outside a class
Probably. I use the cogs method
class?
yes same
yup
no no.
You dont understand.
1 sec pls
bro everyone is now looking down on me because i dont find myself comfy on cogs
no need for "self"
main.py is just loader. it loads shit.
you have a cogs folder, in there, you put your classes for various commands/categories for commands.
Don't just copy paste
were not looking u down
we love umava
๐ you just havent experienced having a massive bot yet lol
we love u mava
^^ ๐ญ
dude, you need to do "client = commands.Bot(command_prefix=".", intents = discord.Intents.all())"
client = commands.Bot(command_prefix=".", intents = discord.Intents.all())```
Uhhhhhhhhhhhhhhhhhhh, is having a 600+ lines bot on main.py file alot
Medium
Oh alright
TYSM IT WORK MAVA
try to start sorting things in cogs
before its too late
No problem
๐ญ
I got 2 files. one to connect to my apis and 1 to handle the database. both over a thousand lol
It is too late already dont worry
and thats not even the commands xD
nah 600 you still got time fr
button = discord.ui.Button(label="Create Ticket", style=discord.ButtonStyle.green)
view = discord.ui.View()
view.add_item(button)
view.timeout = None
await message.author.send("You don't have a ticket yet. Click the button below to create one.", view=view)```
how to check if user clicked the button
Set the callback
i dropped the project of the bot for the server because i didnt like the community anymore lmao
there is another errorr ig
And consider subclassing the view instead
u removed the help command
what i did?
show us more of ur code please
can i send u it in my dms?
yes remove the line client.remove_command("help")
import discord, os, json
from discord.ext import commands
class MyBot(commands.Bot):
def __init__(self):
with open("./json/config.json", "r") as f:
config = json.load(f)
super().__init__(
command_prefix=f"{config['prefix']}",
intents=discord.Intents.all(),
application_id = config['application_id']
)
async def setup_hook(self):
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
await bot.tree.sync()
async def on_ready(self):
print('Logged in!')
bot = MyBot()
with open("./json/config.json", "r") as f:
config = json.load(f)
bot.run(config['discord_token'])
config.json
{
"discord_token": "",
"application_id": 123,
"prefix": "!"
}
bro's a coding god
lol
i remove the help
I think he is following a tutorial atm ๐ญ , that might be too much
man I feel so dumb lol
we all started in tutorial hell
agreed
SEE I CANT EVEN SPELL RIGHT
can i send u all of my code in dms?
ofc
Just send it here. Use the 3 tick method. 3 of these -> `
you could read and open the file just one time instead of two
my code
This is like a year old code
I could update it but it's not relevant lol
Hey @rose thistle!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
bruh
use their pastebin!
You might also consider using a .env file instead of json
he sent the token too
so it wouldnt be a good idea ig
lol
This is why you use a separate file to hold your important shit
Aw man why not ```py
ยฏ_(ใ)_/ยฏ
NOOOO
I still need to fix my issue
I tried doing it but I can't coz I'm stupid lol
what's your issue
I'd love to help man but I am not that good
frrrrrr
ik i told him to change it
Before having my issue I was like: "before sending let me search if I can see something bout this" but then I didn't understand lol
my issues are usually unique lol
Tho I'm making huge improvements lately with discord.py
Oh damn
what are you doing in self.update? maybe your interaction is expiring (it lasts 3sec)
AAHH
you may want to defer at the start of your callback
What is defer?
someone said that before. i disregarded it as fancy talk
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
!d discord.Interaction.followup then respond with this
Returns the follow up webhook for follow up interactions.
Can't you make that 3s longer?
This will extend the duration of the interaction to 15mins
I dont need 15mins xD
I think 15 minutes is the max?
Go for maybe 1
you can't choose how many minutes/seconds the interaction will lasts
So I change await interaction.response.edit_message(embed=embed, view=self) to await defer()?
Ah, sorry
Didn't know
you can only choose to:
- respond within 3 seconds
- defer and respond within 15mins
you'll first defer and later edit
It's a method of the response instance
So wait, what he's trying to do is update an embed with a button to edit it?
ig yes?
I did some googling on how to properly use it
This is my solution:
@discord.ui.button(label="Update", style=discord.ButtonStyle.green)
async def update_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.defer()
await self.update(self.pagenumber)
embed = self.setembed(self.pagenumber)
message = interaction.message
await message.edit(embed=embed, view=self)
yeah
if I'm not mistaken in a library that implements interactions subclasses you could've done something else
(e.g disnake)
does anyone know anything about discord whitelist bot with github and replit?
Does anyone know how to add buttons to your bot message?
Yeah, it simply ||doesn't exist||
Yeah sure what lib
?
Discord.py or a fork
beat me to it
Thanks!
it does what do u mean?
Replit + discord bot = hell
the problem is that it'll hit 429 regularly
cmd = self.bot.get_application_command_from_signature(name=module, cmd_type=nextcord.SlashApplicationSubcommand, guild_id=interaction.guild.id)
``` this is always none
No Error
anyone can help me out
for some reason it gives my big text a white color and the other text a orange colour
so how do i do that
i will dm you
this is like the code so you can see i use colorama
i want like the big text
don't use replit
why
Anyone?
what is none
nvm
can someone help me?
i have a system that creates a command access according to a user's role in the server.
the issue that the bot doesn't accept commands that contains arguments, it's related to the require_access function for sure, but I don't know how can I add the option of adding arguments (str/int/bool/float)
# Define a decorator function that checks if the user has the required access id before executing the command โ
def requires_access(required_access):
def decorator(func):
async def wrapper(interaction: discord.Interaction):
user_roles = [{"role_id": role.id, "access_id": next((item["access_id"] for item in role_access_map if item["role_id"] == role.id), 0)} for role in interaction.user.roles]
if has_access(user_roles, required_access):
await func(interaction, user_roles=user_roles)
else:
await interaction.response.send_message("You are not eligible to use this command.")
return wrapper
return decorator
#code with an argument for example
# Command for getting product information ๐ฆ
@bot.tree.command(name="product")
@requires_access(ADMIN_ACCESS_ID)
async def product(interaction: discord, category : str, users_roles=None):
This issue is because the function which overrides your function in the decorator does not correctly forward arguments. Do you know how decorators work underneath? I'm assuming you got this code from elsewhere?
hi, im using pycord and ive installed pycord and when im import discord, it says discord is undefined, ive imported discord tho
If you don't necessarily know how decorators, I'll happily go into that more deeply
How did you install pycord? Make sure you use the same Python and pip by installing with python -m pip install py-cord
i used python3 -m pip install -U py-cord
Okay, and how do you run your code? Can you try running python3 -c "import discord"?
got a type error
first off, yeah, the issue stems from the overrides of @requires_access(ADMIN_ACCESS_ID), therefore i need to add some sort of an *args to enable arguments, but I just don't know how I combine it within the code.
And no, it's a code I made.
Oh- that would a discord.py or Pycord issue. Since that is different from an import error, I'm assuming the specific issue you're running into is that you're installing pycord to a version other than the one you're runnig
how do i fix that?
But that also because I'm quite new in coding discord bot.
Well, when you run your bot and get an import error, how do you run it?
i can't
i press the run button
and i get an error
Right, so there's more than one issue you have here and I think if I explain decorators from the start you'll realize why. To start of, decorators are just for wrapping functions as you've shown, but they're based on being able to create functions inside of a function. We can for example create a simple printer function like this:
def printer(message: str) -> Callable[[], None]:
def inner() -> None:
# We can access variables in the function this was defined in
print(message)
return inner # Return the function created
hello = printer('Hello world')
hello() # Hello world
hello() # Hello world
Whenever we call hello(), we'll call the function that was created inside of printer(). Note that these variables are not shared, so we can have multiple printers at the same time:
hello = printer('Hello world')
goodbye = printer('Goodbye')
hello() # Hello world
goodbye() # Goodbye
If the variables were shared between calls, these would've both printed out Goodbye. Accidentally sent this, so I'll continue in another message
yeah, i can see what you mean
Decorators take advantage of this to wrap functions, so we create a new function which calls the previous function inside of it. This function prints the elapsed time: ```python
import time
def timefunc(func: Callable[[], None]) -> Callable[[], None]:
def inner() -> None:
start = time.perf_counter()
func()
print(time.perf_counter() - start)
return inner
def sleeping():
time.sleep(2)
timed_sleep = timefunc(sleeping)
timed_sleep() # 2
We can run code before and after the function we wrap. However, we'll run into issues like you have if we try to give it arguments and you'll see why if you print and compare the functions: ```python
print(timefunc, sleeping, timed_sleep)
<function timefunc at 0x...> <function sleeping at 0x...> <function timefunc.<locals>.inner at 0x...>
We have created a new function for timed_sleep which is not the same as sleeping. This is hidden when we use the decorator syntax: ```python
@timefunc
def sleeping():
time.sleep(2)
Same as the following
def sleeping():
time.sleep(2)
sleeping = timefunc(sleeping)
Now, onto fixing the problem...
I keep getting this error when running my bot: py 'module' object is not callable File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 64, in LatexBot @asyncio.coroutines ^^^^^^^^^^^^^^^^^^ File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 29, in <module> class LatexBot(discord.Client): TypeError: 'module' object is not callable
This is the target of the error: py @asyncio.coroutines def on_ready(self): print('------') print('Logged in as') print(self.user.name) print(self.user.id) print('------')
This is line 29: ```py
class LatexBot(discord.Client):
Me?
or @commands.Cog.listener() if inside cog
For us to be able to give a function arguments when it is wrapped by a decorator, we need to match the syntax of that function perfectly. Think about which def is the one being returned, in this case it is inner() I don't want to confuse you with the typehints, so I've stopped using them here:
def timefunc(func):
def inner(*args, **kwargs) -> None:
start = time.perf_counter()
func(*args, **kwargs)
print(time.perf_counter() - start)
return inner
def sleeping(duration):
time.sleep(duration)
timed_sleep = timefunc(sleeping)
timed_sleep(3) # 3
Your code uses three functions though, and that's because if you notice I didn't have parenthesis in my decorator example before. You have a function, which creates a decorator, which creates a function to replace the function: ```python
def timewarn(duration):
def decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
func(*args, **kwargs)
if time.perf_counter() - start > duration:
print('Warning! Function took too long')
return wrapper
return decorator
@timewarn(2)
def too_long():
time.sleep(3)
Equivalent to the following
decorator = timewarn(2)
def too_long():
time.sleep(3)
too_long = decorator(too_long)
As you'll see in this code, **you should add** `*args, **kwargs` **to** `wrapper()`. -but you'll run into another problem. Since we're replacing the function, when discord.py is reading the typehints it'll be reading *the returned function* (the same way, when we print it we get a different name):
```python
print(too_long) # <function timewarn.<locals>.decorator.<locals>.wrapper at 0x...>
To fix this, we need to copy over this information - which functools will help you with: https://docs.python.org/3/library/functools.html#functools.wraps
Our timewarn function, should therefore look like this:
import functools
def timewarn(duration):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
func(*args, **kwargs)
if time.perf_counter() - start > duration:
print('Warning! Function took too long')
return wrapper
return decorator
Can I get help here?
@uneven hearth, in the end... you want to add *args, **kwargs to your wrapper() and decorator wrapper() with @functools.wraps(func)
Where? Which run button?
in vsc
In the bottom right, it'll say which Python version it is using. You can also open the Command Pallete with Ctrl + Shift + P and find "Select Interpreter". Make sure this is the same version as the one you get when you run python3 -V
@asyncio.coroutines is a file inside of the asyncio module: https://github.com/python/cpython/blob/main/Lib/asyncio/coroutines.py
The error here is correct, because you're trying to call a file which is considered a module. To fix the error, either remove the s at the end to make it @asyncio.coroutine which I assume it is you're looking for.
That is very old though, and you should be using async def instead. Change def on_ready(self): to async def on_ready(self): and remove the @asyncio.coroutines line
Okay I did it. So remove the @asyncio.coroutines?
Or just remove the S?
Depends on which solution you're looking for, I recommend removing the entire line as I stated in the second solution (third paragraph)
I just decided to remove entire line, now I get: py Client.__init__() missing 1 required keyword-only argument: 'intents' File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 31, in __init__ super().__init__() File "C:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 147, in <module> LatexBot() TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'
@client.command()
async def test(ctx):
with open("kurac.json") as f:
guild = json.load(f)
if int(ctx.guild.id) in guild:
await ctx.send("kurac")
Traceback (most recent call last):
File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 179, in wrapped
ret = await coro(*args, **kwargs)
File "/home/miricmatija2/institut/as.py", line 15, in clear
if int(ctx.guild.id) in guild:
TypeError: argument of type 'int' is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 335, in invoke
await ctx.command.invoke(ctx)
File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 916, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/miricmatija2/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 188, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'int' is not iterable```
any who can help?
do you know what this means?
File "/Users/emlynphoenix/clothing.py", line 1, in <module>
import discord
File "/opt/homebrew/lib/python3.11/site-packages/discord/__init__.py", line 22, in <module>
from ._version import *
File "/opt/homebrew/lib/python3.11/site-packages/discord/_version.py", line 30, in <module>
from importlib.metadata import PackageNotFoundError, version
File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/__init__.py", line 17, in <module>
from . import _adapters, _meta
File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/_adapters.py", line 3, in <module>
import email.message
File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/message.py", line 15, in <module>
from email import utils
File "/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/utils.py", line 28, in <module>
import random
File "/Users/emlynphoenix/random.py", line 6, in <module>
print(''.join(letters))
^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found```
hey, sorry for not replaying. you mean to change the decorator from function to this ( @functools.wraps(func))?
any who can help please?
Ah- this would be your code's issue then. Let me simplify the traceback and we can look at it together: ```python
Traceback (most recent call last):
"/opt/homebrew/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/utils.py", line 28, in <module>
import random
File "/Users/emlynphoenix/random.py", line 6, in <module>
print(''.join(letters))
^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found
When you import Pycord, it ends up importing `random` and the issue is that instead of importing *the real random* it is importing *your file named* `random`. In this file, your code has an issue.
```python
sequence item 0: expected str instance, int found
Tells you that in the sequence (which is letters) at the item 0 (which is the first one) it wanted a string but you gave it an integer.
Something is wrong with your code, where letters is a list of integers when it should be strings
i saw it now
now i understand that
thank you!
this is my code```py
import discord
TOKEN = ""
intents = discord.Intents.all()
intents.members = True
bot = discord.Bot(command_prefix = '$', intents=intents)
bot.remove_command('help')
@bot.event
async def on_ready():
print("Bot is online!")
@bot.command()
async def group(ctx):
embed = discord.Embed(description=f"Roblox Group: https://www.roblox.com/groups/7952306/Skylinee#!/about", colour=0xa3fdee)
await ctx.reply(embed=embed)
bot.runt(TOKEN)```
All of the messages I sent between I started answering you to the end is a response, so I recommend starting from the first one and reading down to me pinging you with the summary ๐
The error is in the file named random.py. Now, even if you fix the issue there you will have other problems in the future. You should rename that file to something else
@minor totem can you finish helping me please?
This may be because you're using cold that is too old for the version of the framework you're using. The error here is telling you exactly what is wrong: it is missing the argument named intents. In other words, you have not given it intents when it needs to have that
I was about to respond ๐
I added this super().__init__(discord.Intents)
class LatexBot(discord.Client):
def __init__(self):
super().__init__(discord.Intents)```
you need an intents object
I'm guessing that the issue here is that ctx.guild.id is already an integer, so when you try to turn it into an integer Python tries to convert it as if it was a string. Just remove int(...) and leave what was inside of the parenthesis
def __init__(self):
super().__init__(intents = discord.Intents.default())
it's also a keyword argument
so you have to specify intents = ...
Good try, you need to give it an instance with the specific intents you want to use. Keep in mind that if you do not have the right ones, the bot will not work as expected. Depending on whether you use discord.py or Pycord, I believe there should be a guide for each which explain intents good
So: py class LatexBot(discord.Client): def __init__(self): super().__init__(discord.Intents.default())???
@smoky sinew sent the code you may want to use. In the error it says "keyword-only argument" which means that when you pass it you need to do intents=, otherwise it would be a "positional argument".
Yep, eventually you gotta understand what you're doing.
dont work
you have to specify intents = ...
super().__init__(intents = discord.Intents.default())```
yes
uhh i dont have a file called random.py
/Users/emlynphoenix/random.py?
Okay so, when running I get: py Traceback (most recent call last): File "C:\Users\Clicx\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "c:\Users\Clicx\OneDrive\Documents\HeXit\latexbot.py", line 72, in on_message if chanrestrict.check(message): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Clicx\OneDrive\Documents\HeXit\chanrestrict.py", line 19, in check if message.channel.is_private: ^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'TextChannel' object has no attribute 'is_private'
Is that in intent I need?
no, that attribute was simply deleted
do you want to check if a channel is a DMChannel?
Okay, then that means that guild is an integer. See, when you do in guild Python will try to loop through guild which isn't possible when guild is an integer. Are you sure that the JSON file you're loading is correct?
So this: py def check(message): allow = False if message.channel.isinstance(): allow = private???
The error would be a bit different if that was the case. This error is a bit weird, but that is because the code you're using is very old and assumes it is running on another version of discord.py
I would recommend trying out a different project, unfortunate that this one didn't work out!
Can't I simply update this one and modify it?
only what i have in json file is 1042533707464060979 one guild id
There will be several things you need to do to fix it I believe. Can you link it?


