#discord-bots
1 messages · Page 269 of 1
How can I fix this errors?
https://paste.pythondiscord.com/KGAA
I have been struggling with this for a few hours now
so like this instead
i dont see any errors
Cannot find reference 'edit_message' in '() -> InteractionResponse' Cannot find reference 'send_message' in '() -> InteractionResponse' Cannot find reference 'send_message' in '() -> InteractionResponse'
its a problem with pycharm that it cannot read typehints properly if you have actual traceback come back
try
What about Unresolved attribute reference 'message' for class 'Counter'
you assign it but you did not tell the class it will have such attribute
so it is warning you
but you assign it when sending message
im using a file.pkl to store object data
when i try to read what i stored without closing the python script it works
the problem is when i stop the python script and i start it again it should load the data from the file from the last session but is not reading any data despite it being there
Is there no way to fix that eaither?
well this one you can fix
Do you know how?
class Counter(discord.ui.View):
message: discord.Message
...
Still same, Unresolved attribute reference 'message' for class 'Counter'
what did you add
message: discord.Message
class Counter(discord.ui.View):
def __init__(self):
super().__init__()
self.clicked_users = []
self.vote_count = 0
message: discord.Message```
did i put it inside any method here
Oh my bad,
class Counter(discord.ui.View):
message: discord.Message
def __init__(self):
super().__init__()
self.clicked_users = []
self.vote_count = 0```
Yes, it disappeared
ok these errors are breaking my brain
foken all of them
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yes i know but every little thing i do doesn't work
show code then
await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.
New in version 1.1.
its awaitable as you can see
bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=discord.Intents.all()) why you create a Bot instance if you literally created a subclass
¯_(ツ)_/¯
i am not a expert i just followed the guides
how exactly do i use this?
stats(str(await discord.Attachment.read(blueprint)))
Looks like interaction expired or you deleted the message
got it working finally
its a blueprint for a game called Virtual Circuit Board
also how do i get slash commands
Button labels can be custom emojis right?
If so, is the syntax not <:emojiname:ID>
im looking though but im not exsactly sure how it works
is it just @client.tree.command() instead of @bot.command()
No there is special kwarg for that
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
emoji kwarg ^
Yes and it takes Interaction and not Context
!d discord.PartialEmoji.from_str
classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").
The formats accepted are...
I'm just using this, fine no?
so how do i make the bot to return failled response when room id is incorrect
with open("admins.txt", "r") as f:
if str(ctx.user.id) in f.lines().split():
admin = 'True'
else:
admin = 'False'
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 53, in setup
if str(ctx.user.id) in f.lines().split():
AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'
anyone know why this doesnt work
why are you setting admin to a string, but with true or false? just set it to a boolean 💀
Idk what that is
Booleans are a special type of value that can be either True or False
with open("admins.txt", "r") as f:
if str(ctx.user.id) in f.lines().split():
admin = 'True'
else:
admin = 'False'
Can be compressed into
with open("admins.txt", "r") as f:
admin = str(ctx.user.id) in f.lines().split()
oh I see now
with open("admins.txt", "r") as f:
admin = str(ctx.user.id) in f.lines().split()
embed.add_field(name='Admin', value=admin, inline=True)
await ctx.response.send_message(embed=embed)
gives me an error @sick birch
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 57, in setup
admin = str(ctx.user.id) in f.lines().split()
AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'
It's f.readlines() iirc
did not work
@client.tree.command(name='account', description='view your account')
async def setup(ctx: discord.Interaction):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT 1 FROM users WHERE memberid = ? AND guildid = ?', (ctx.user.id, ctx.guild.id,))
data = await cursor.fetchone()
if data:
await cursor.execute('SELECT coins FROM users WHERE memberid = ? AND guildid = ?', (ctx.user.id, ctx.guild.id,))
(coins,) = await cursor.fetchone()
embed = discord.Embed(title=f"{ctx.user}'s Account")
embed.add_field(name='Coins', value=coins, inline=True)
with open("admins.txt", "r") as f:
admin = str(ctx.user.id) in f.readlines()
embed.add_field(name='Admin', value=admin, inline=True)
await ctx.response.send_message(embed=embed)
else:
await cursor.execute("INSERT INTO users(memberid, guildid, coins) VALUES (?, ?, ?)", (ctx.user.id, ctx.guild.id, 100))
await ctx.response.send_message("Account made!")
await db.commit()
this is my full code
readlines() will include the trailing newline of each line
Soooo
So you're comparing "100" to "100\n"
Hence it will always be False
Either read() and split on newline or add the newline to the id
Hey guys I had a question about interactions in nextcord and discord. Is nextcord.Interaction or discord.Interaction limited only to slash commands or can it be used for prefix commands as well?
It's only for interaction stuff, like app commands, buttons, drop-downs, ...
For prefix and hybrid you use Context
so discord.Interaction won't work for hybrid commands right?
Yes
I wrote a basic code that gives or removes roles in a server and it works in 1 server but doesn't work in another. It has the same permissions in both servers but the error code says "missing permissions". What da heck?
Tbh hybrid commands also categories as slash commands so it might work for them
discord.py will convert discord.Interaction object into a discord.ext.commands.Context when using hybrid commands
Check if your bot role is higher in hierarchy than the role you are giving or remove
This is the code. But it works perfectly fine in another server so it's a permissions problem or whatever. Which also makes no sense.
role_name = "Voice Chat"
role_emoji = "🎤"
message_id = 1128780883340578976
@bot.event
async def on_raw_reaction_add(payload):
guild = discord.utils.find(lambda g: g.id == payload.guild_id, bot.guilds)
if payload.emoji.name == role_emoji and payload.message_id == message_id:
role = discord.utils.get(guild.roles, name=role_name)
print(role, type(role))
if role:
member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
print(member, type(member))
if member:
try:
await member.add_roles(role)
except Exception as e:
print(e)
The role that I'm giving is literally just for pinging. It has no special permissions
If it's above your bot role then it will still throw error
Then how do I bring it down?
I just tested it out but discord.Interaction works for prefix commands too
for sending the message
Or vise versa
Hey, im trying to send a auto message but having trouble. Dont know how to start the loop. This is what I have.
@tasks.loop(seconds=10)
async def auto_send():
channel = vini.get_channel(1123454159543357540)
embed = discord.Embed(colour=0x182D9F)
embed.set_author(name="Just Some Subtle Reminders")
embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #┃commands \n \n Learn how to join our team over here #┃how-to-join"
embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
await channel.send(embed=embed, delete_after=60)
Show the code for it
.
its just a hello command
@bot.command()
async def hello(interaction: discord.Interaction):
await interaction.send("hi")
I remember answering this
From your roles in server settings
That's not how parameters works
How do I make the bot the higher hierarchy @turbid condor
The interaction argument is actually a discord.ext.commands.Context
.
Hmm. Let me check
Sorry, slow responder here
Did you forget or it's just me you need to respond to an interaction
no, I'm trying to figure out 2 things here
- If interactions were limited to only slash/hybrid commands
- why does
interaction.sendwork in discord.py? It's a nextcord statement not discord.py so in discord.py it should beinteraction.response.send_message()howeverinteraction.send()works when it is not supposed to be in discord.py
That's because it's actually a context object, just print it
I got the first part, thanks for the answer
Bro are you serious. It took me whole fucking day just to find out that I had to delete the role and remake it and it works
Instead of remaking u could have just dragged them down from the eight dots that show on left side
I tried
It was stubbornly going back
So I deleted it and remade it
And now it's on the bottom
You sure u were saving it
The reorder button right? Yes I clicked save and everything
Maybe it was glitched or something
Btw thx for the help
I was about to blow my brains out
Last resort was administrator permissions
That wouldn't have worked either
Damn
Since your bot would still been lower in hierarchy
class AutomaticModal(ui.Modal, title="Support"):
def __init__(self):
super().__init__()
issue = ui.TextInput(label="What is your issue?", placeholder="Please describe your issue here in as much details as possible!", style=discord.TextStyle.long)
async def on_submit(self, interaction: discord.Interaction):
embed=discord.Embed(title=" ", description="Our bot wasn't able to locate a solution to this problem. If you would still like support on this issue, please create a ticket describing your issue!", color=discord.Color.red())
await interaction.response.send_message(embed=embed, ephemeral=True, view=Button())```
using this code, if for example someones issue = "asd" how would i make the bot respond with a different message rather than the default message? is this possible
That's bull
U mean the embed description should be changed each time it is sent?
Hey, is it possible to have a function that's basically the opposite of on_ready ? Like it would do a final command before the bot shuts down
Oh, sorry what was it?
Don't think so there is something like that but u can use on_disconnect tho this can happen as many times as your bot disconnects
You could also use the bot's _aexit_
if data:
await cursor.execute('SELECT coins FROM users WHERE memberid = ? AND guildid = ?', (user.id, ctx.guild.id,))
(coins,) = await cursor.fetchone()
coins = await cursor.fetchone[int(0)]
coins = coins - rcoins
embed = discord.Embed(title='Coins Removed')
embed.add_field(name='Coins Removed', value=rcoins, inline=True)
embed.add_field(name='Coins', value=coins, inline=True)
embed.add_field(name='Author', value=ctx.user.id, inline=True)
await ctx.response.send_message(embed=embed)
await cursor.execute("INSERT INTO users(memberid, guildid, coins) VALUES (?, ?, ?)", (user.id, ctx.guild.id, coins))
how do I remove the coins?
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 75, in removecoins
coins = await cursor.fetchone[int(0)]
TypeError: 'method' object is not subscriptable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'remove-coins' raised an exception: TypeError: 'method' object is not subscriptable
Thx @turbid condor and @vocal snow I will experiment now
Is there a way to bypass the 1024 character limit for an embed? It’s for a server info command
No
hasn't the character limit been increased now?
Use many embeds
better add fields with blank name

Tried this, it’s the server emoji list that exceeds 1024 characters itself

This is the code I’m using, is there a way I can alter it so that it doesn’t exceed the embed limit?
emoji_list = ' '.join(str(emoji) for emoji in emojis)
embed.add_field(name='Emojis', value=emoji_list, inline=False)
else:
embed.add_field(name='Emojis', value='No emojis in this server', inline=False)```
you can paginate the embed
so that it shows some emojis on first page and other on next
Ive found a way to list some of the emojis and then out a counter at the end of the message for example [emoji1][emoji2][emoji[3] +5
This shows the first set of emojis then calculates however many is left that aren't shown. However the code is listing the emojis below eachother even though ive set inline to false
emoji_list = [str(emoji) for emoji in emojis[:15]]
emoji_count = len(emojis)
emoji_remaining = max(emoji_count - 15, 0)
emoji_list_str = '\n'.join(emoji_list)
emoji_list_str += f'\n... +{emoji_remaining}'
embed.add_field(name='Emojis', value=emoji_list_str, inline=False)
else:
embed.add_field(name='Emojis', value='No emojis in this server', inline=False)```
wait i figured out why its listing them under eachother 

Hey, dropping my whole code here basically, so I basically am setting up a dropdown with different modals connecting to those dropdowns. I am just gonna show just one modal as its a lot. But basically when I run the command ".invite" nothing happens, no error.
Dropdown:
@vini.command()
@commands.has_permissions(administrator=True)
async def invite(ctx):
embed1 = discord.Embed(colour=0x182D9F)
embed1.set_author(name="Rane's Staff Application")
embed1.description ='**Please click the dropdown and press on the role you are seeking to join as.**'
embed1.set_image(url="https://media.discordapp.net/attachments/991482958026379274/1123479665391177908/THEAPPLY.png?width=1440&height=323")
await ctx.send(embed=embed1, view=InviterView())
class Inviter(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Staff", custom_id="staff"),
discord.SelectOption(label="Player", custom_id="player"),
discord.SelectOption(label="Studios", custom_id="studios"),
discord.SelectOption(label="Content Creator", custom_id="content")
]
super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
async def callback(self, interaction: discord.Interaction):
channel = vini.get_channel(1123456106740584528)
guild = vini.get_guild(1123453068952993802)
if interaction.custom_id == "staff":
modal1 = staff_modal()
await interaction.response.send_modal(modal1)
await modal1.wait()
elif interaction.custom_id == "player":
modal3 = player_modal()
await interaction.response.send_modal(modal3)
await modal3.wait()
elif interaction.custom_id == "studios":
modal4 = studios_modal()
await interaction.response.send_modal(modal4)
await modal4.wait()
elif interaction.custom_id == "content":
modal5 = content_modal()
await interaction.response.send_modal(modal5)
await modal5.wait()
class InviterView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Inviter())
Im actually just not gonna show the modal as I know thats not the issue at hand
Its just having issues showing the view.
Can you show where you define your bot instance
this?
vini = commands.Bot(command_prefix = '.', intents=discord.Intents.all())
if interaction.custom_id == "staff":
modal = staff_modal()
elif interaction.custom_id == "player":
modal = player_modal()
elif interaction.custom_id == "studios":
modal = studios_modal()
elif interaction.custom_id == "content":
modal = content_modal()
await interaction.response.send_modal(modal)
await modal.wait()
bit of a cleaner way of doing what you're doing, personal preference
Are you using discord.py?
Can u show the buttons u created and how are u sending them
I mean your code
Try adding the select first before initialising the super.
Can you help me?
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.
seems like your bot doesnt have perms to create slash commands
No i use slash command
if it isn't that, just make sure ur bot has high permissions (or good enough permissions)
that doesn't matter, still needs intents iirc
iirc you do, not entirely sure
What will it be then
Now i create prefix?
yo long time no see :)
You only need the application commands scope when inviting the bot
Yes
ANSWER ME💀💀
Hi there! Where have you been? 🐈
How fix?
exams 
ended rn but prac exams are still going on
@shrewd fjord
Help me?
That explains it
class disnake.Interaction```
A base class representing a user-initiated Discord interaction.
An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.
New in version 2.0.
- Your bot isn't in provided server
- Bot was not authorised with
applications.commandsscope in that server
just telling about wht can happen next
Now how to fix it?
kick the bot
bruh
if you have invited without appcommands scope already
Authorise it again but with that scope
Waite
why not doing any development on the bot xd You're on break or something
We need promotion
Done
There are plans but why waste efforts for nothing
ohk
restart the bot and check

......
both are wrong imo
How to fix man?
use InteractionBot if you dont want prefix
Inter?
have to check docs
Where?
wait is your bot even in the guild for which you are trying to sync command
Can you help me?
nope i know nothing but disnake
I actually managed to contact a 100k youtuber (whirow to be precise) but he said he's not going to make vid on it 😭
just invite the bot in your test server with applications.command scope enabled
why 
try ntts ig
Ok
I doubt he does bots ads
he does some bot scripts tho still not sure 💀
Right?
Ig we need to target a lot of smaller youtubers
copy invite link
kinda makes me think why would they do for free lol
Now done
Cause not enough servers
mhm
Stupid circle
Are you kidding me?
I was planning to do that after site, but site is after 500 servers
use the invite link to invite the bot in your server
Donee
i was telling to exenifix lol
I did the same error but the same error didn't fix
restart the bot and try again
Not fixed
long way to go, you should start in some days
i think, i mean not about the site, about premium cmd
They are easy to do
Man look i mean command
Just one role can use slash command
How?
hmmmmmm........ try
bot = commands.InteractionBot()
The monetisation itself is difficult cause we need a site, security and payment processor
Me being in Russia makes things even more difficult
yes but just telling for now keep something like premiumbut under development, so that if ytbers find stuff interesting you hand over a premium key ig
Remove one error but didn't fix
at this point idk lol
💀
Only 40 servers in half of year
are you using virtual environment?
use then...
python -m venv .venv
this should create a virtual environment for you
............. um did you activate venv?
!venv
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
now activate it
now just do pip install discord.py
and this shouldnt show any error
actually there aint good free host
mhm...
may try OceanHost or something
let me try
its ip is used anyway
not good for your bot
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Affordable and powerful VPS Hosting in Europe. Linux, Windows and Storage VPS available from 1.99 EUR/month.
!host
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Hi!
I'm making a discord giveaway bot but I'm having problems getting the users who reacted to the giveaway embed. I have the ID of the embed, and I'm 100% sure it is right since the bot can react to it, however gwmessage.reactions gives an empty list, even when I and the bot have reacted to it as well.
Here's my relevant piece of code:
await gwmessage.add_reaction(":tada:")
await asyncio.sleep(delta.total_seconds())
print(gwmessage.reactions)
reaction_users = gwmessage.reactions[0].users().flatten()
reaction_users.pop(reaction_users.index(bot))
It was giving me an IndexError, so I printed gwmessage.reactions and it is empty. Any clues why that would be?
is it this line that you're getting the error on?
reaction_users = gwmessage.reactions[0].users().flatten()
If so, it's because you're using outdated code
yes, since reaction_users is empty
Thank you, I didnt know that flatten() was no longer used, however the problem is with the gwmessage.reactions, that's empty as well
ah, do you have the reactions intent?
yes, I'm using intents = discord.Intents.all()
how are you getting gwmessage
they are all enabled in the dev portal as well
async for message in interaction.channel.history():
if not message.embeds:
continue
if message.embeds[0].title == embed.title and message.embeds[0].colour == embed.colour:
gwmessage = message
break
I know gwmessage is the right message, since await gwmessage.add_reaction(":tada:") works and puts the reaction onto the right message
I'm guessing then it isnt updating with the new reactions
you need to fetch the message to get the updated stuff
await interaction.channel.fetch_message(gwmessage.id)
welp wouldn't using buttons and a database would make it look better?
It would
it certainly would, I'm planning on rewriting that part soon, for now though I want to get the basics right, and I also hate working with buttons lmao
thank you, I'll try fetching it again then
welp u can try alternate approach of storing the ids of the ppl who react to the msg too instead of checking who made a reaction since the reactions can be removed by some one who has perms and can also get deleted whereas incase of storing them this problem would not occur
That would take out the functionality of opting out of the giveaway though no?
welp why would one join a giveaway if he has to opt out?
I don't know, but it's much more straightforward for end users this way
I am just giving a suggestion it all depends on you in the end since you are coding
yea ty this project is far from being finished lol so this is not it's final form
there is an alternative for this too
I have found what the error is, when I fetch gwmessage.reactions again it's value is [<Reaction emoji=':tada:' me=True count=2>] so it doesn't list any users
that's because users isnt an attr, it's a method
You need to do something like this (this is on the official docs, theres always great examples)
but where is the message defined in this example? what message does reaction.users() use for getting them?
right now you have gwmessage.reactions, this is a list of Reaction objects, you'd get the 1st item with the index
gwmessage.reactions[0].users()
ooh I see, thank you!
Hey, how can I mention @everyone?
just write it
can i mention @everyone in embed?
It won't ping
Only description
Yeah should work
I dont think that pings them
it only pings if its in the message content
as chrispy said
Hello anyone Can Fix this Why Just Select One?
The embed variable you made is static, it will never change if you don't make it so
How to fix it?
@naive briar
Fix what
Fix embed random
What does that even mean
Do you mean it should send a random answer?
Yes
I mean how to fix random answers
Look why just select one
I mean select random
yo, how to fix this error?
startswith first arg must be str or a tuple of str, not bytes
i am getting it while creating webhook with custom avatar
Please Help me
And u want it to send 3 different embeds or just option
cause you randomize it outside of a command
move it inside so it is choosing random on each command call
send code
And traceback too
error?
.
!tracrback
full traceback not just 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.
The avatar needs to be a bytes object, not a string
why not just directly use image_bytes as avatar instead of saving it
Great, they're using requests and aiohttp together
bruh
!blocking 
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
long ass embed
cringe
aiohttp my beloved
!yt
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
ah
why do i put heres i forgot
pls how can i delete all file content ?
A file as in an attachment?
You want to delete the files of a message without deleting the content?
nah i mean a simple json file
in your desktop
this is the discord bots channel, you should ask in #python-discussion or claim a help channel next time.
But to remove the data in a json file you can open it with open() in "w" mode, and just write "{}" to it
If you have worked with open() or files before I would suggest reading up on that first
ok thx
cannot work with r+ mode ?
r+ is for reading then writing
if you just want to write empty json to it then you can use w directly
if you want to read then write then use r+
make sure to seek after reading
okay but i can't read with w ?
no
yeah that's the problem
i want to take infos from the file then delete file content and rewrite
ok thx
@meager chasm something like that (without seek) ?
can see your def setup()?
oh nvm had the wrong token
ok
you haven't defined "file" anywhere
oh yeah my bad bcz i changed names
!with
The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.
with open("test.txt", "r") as file:
do_things(file)
The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.
For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.
yeah ik
👌
@meager chasm could you help me with that case please ? :
with open("vouches.json", "r") as filer :
jsoncontent = filer.read()
vouchesl = json.loads(jsoncontent)
vouchesl.append(f"**Submitted feedback by {ctx.author.name}**\n\n> **Product** ・ `{product}`\n> **Seller** ・ <@>\n> **Service rate** ・ `{rate} / ⭐⭐⭐⭐⭐`\n> **Feedback** ・ `{feedback}`")
with open("vouches.json", "w") as filew :
filew.write("")
json.dump(vouchesl, filew)```
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "f:\mesdraps\vouches_bot\main.py", line 38, in feedback
vouchesl = json.loads(jsoncontent)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: JSONDecodeError: Expecting value: line 1 column 2 (char 1)
Don't write an empty string
Write an empty json object
Like {}
And make sure your json is valid before you read it
okay
if i provide a emoji to my command, it just returns the emoji id like :abc:
how can i get the asset?
use the id
nah i need to get the asset to convert it into bytes
ah
ctx.guild.region
does this still exists?
its not working for me anymore
like it has been changed\
its deprecated
File = discord.File(filepath)
await message.channel.send(file=File)
it literally tells you in the comment
how do i give a description to a argument
what library?
this tells me nothing
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
you just say description="idk"
how can I make it read the url
The [0][url] doesn't work as url is more than one character. Just l also doesn't work
[{"id":"7jk","url":"https://cdn2.thecatapi.com/images/7jk.png","width":638,"height":478}]
[{"id":"7jk","url":"https://cdn2.thecatapi.com/images/7jk.png","width":638,"height":478}] this is what get_cat returns?
yes
async def get_cat():
async with aiohttp.ClientSession() as session:
async with session.get("https://api.thecatapi.com/v1/images/search") as image:
if image.status == 200:
json_data = await image.json()
return json_data
!e ```py
data = [{"id":"7jk","url":"https://cdn2.thecatapi.com/images/7jk.png","width":638,"height":478}]
print(data[0]["url"])
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
https://cdn2.thecatapi.com/images/7jk.png
Traceback (most recent call last):
File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 135, in cat
embed.set_image(kitty[0]["url"])
TypeError: Embed.set_image() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.set_image() takes 1 positional argument but 2 were given
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
url is keyword only
you know what i mean by that?
not sure but I think I can assign [0][url] to a variable and pass that variable as a parameter
nope
you can do it directly in the set_image
thats not what is wrong
if the argument is keyword only it means that:
# wont work
my_function(argument) # positional
# will work
my_function(argument=argument) # key-word
``` see the difference?
ahh
is there a way to obtain the epoch time when the command was executed?
what's wrong with getting the current epoch time first line in the command?
you know there's a discord utils for that
!d datetime.datetime.now
classmethod datetime.now(tz=None)```
Return the current local date and time.
If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).
If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.
This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
example
import discord
import datetime as dt
current_time = dt.datetime.now()
some_format = discord.utils.format_dt(current_time, style="F")```
discord.utils.MISSING```
A type safe sentinel used in the library to represent something as missing. Used to distinguish from `None` values.
New in version 2.0.
for each of the keyword I can have this?
they're all in the docs link...
also, it's the last letter...
all possible flags are in the docs
thanks I'll check it out
check the link above for me
I don't get why there's
style = None as kwarg
but in the docs itself, it states that f is default? 🤔
why / when would you use this?
cause if you dont pass any flag the discord uses this format as default
so why doesn't it basically = "f" ?
its when you want to assign default value but dont want to use None since it could be default as well
discord/utils.py lines 1236 to 1238
if style is None:
return f'<t:{int(dt.timestamp())}>'
return f'<t:{int(dt.timestamp())}:{style}>'```
had a mild stroke reading that
src/env.py line 14
default: t.Any = MISSING```
it doesn't work though, the organization doesn't really bother me rn lol
it not working does.
here for example i would like to set default value as None for something
i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once
and MISSING comes in clutch
ah, wow
it's basically a value with no specific meaning
hence when used, it'll error... (and None wouldn't, as it could be a valid value)
yeah something like that
so it's more like a placeholder?
its like actual None
mhm, I see
I'd have to find use cases for that in my code
Hello, I am trying to make a blackjack discord bot for my server. I have spent the last few hours learning and coding the bot and am encountering an issue with BREAK. Does anyone have many solutions or recommendations?
break can be only used within loops
you are outside a while loop you defined above already
Thanks. I am new to python and am trying to learn. I managed to fix the issue!
On discord bots, is it possible for discord.py to register a command like "/token" and then it will ask for a bot token and instead of the bot using say for example "TRXNCHES BOT" it will now be online on "NEW USER BOT" and it host that bot? or is that not possible, i know its possible for discord.js but im not sure about discord.py
why would you want to host a bot within other bot
for premium users to use their own branding of the bot
it is possible
is there docs about this? or somewhere i can read up
isnt it better to make bot open source so everyone can host is how they want?
Im working on making a public bot for fivem servers, but i'm stumped at this part
what would it be under "premium" is nitro ive scrolled for around 30 minutes trying to find an answer i cannot see anything about this
What do you mean?
Are you trying to check if a user has nitro?
well cause nobody really do such cases it is possible but i dont think anyone is able to help you with all of it at least here
no, i'm trying to create a slash command that can register a bot token and then bring the given token online hosting the bot.
What part are you stumped on
anywhere i can see on the docs about this
you want to create a new bot with that token?
So if i have the bot online, users can invite the bot to their discord, and then use a command like "/token" and then pass a token into it, if the token is a valid bot token, it can then bring the bot of that token online and host it
yeah that isn't hard to do, but the bot would have no commands
Is it possible that the bot can host the bot with the same commands as the original bot? in discord.js it is possible to do? or is there a way to host a set of custom commands with the given bot token
I don't know of a way to do that, I was thinking you'd have to create multiple instances of the bot class then update those with the new tokens, @slate swan do you know?
no idea never tried to
Yeah I don't really know sorry, @slate swan
It's possible but it's gonna be more complex than I thought
try asking here discord.gg/dpy
ty
for the help!
already did above but let me say it again:
- you are choosing the random item outside the command
- do it inside so it gets choosen on each command run
i think you shouldn't store the random.choices as a variable. it will stay as what it is
unless you have it to be inside a loop
then its value will change
and basically this
!e ```py
import random
random_number = random.randint(1, 10)
def get_random_number():
print(random_number)
get_random_number()
get_random_number()
get_random_number()
get_random_number()
get_random_number()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 2
002 | 2
003 | 2
004 | 2
005 | 2
!e ```py
import random
def get_random_number():
random_number = random.randint(1, 10)
print(random_number)
get_random_number()
get_random_number()
get_random_number()
get_random_number()
get_random_number()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 7
003 | 1
004 | 9
005 | 3
i hope you see difference
Can you send me an example.
you literally have example above your message
lol
Man That’s not what I want
so what you want
you are asking why the thing you are choosing randomly dont change on each command ran dont you
and i shown you why
Ok Where should I embed?
what you mean by that?
send your code
the random_number part is just to show you what is the difference between choosing random thing in and outside of a function
obviously i wont give you straight example you can copy paste and make it work
Hi, can someone help me. I have a problem with the select menus, only the first one works and the second one doesn't even give an error, only 'This interaction failed' .
``` select = self.children[0]
select.disabled = True
if "title" in select.values:
await interaction.response.send_message('Test :D (Title)')
if "decs" in select.values:
await interaction.response.send_message('Test :D 2 (Description)')```
@slate swan
full code
Can I send it tomorrow?
you can do whatever you want
Man look glitch why?
When i Again command
He created a new embed why?
cause you made it to
?
how am i supposed to know when you dont even share the code
and where you define embed?
you are sending an embed on each command call so he does
I'm glad you're helping us❤️
found my error, was hoping someone could help. So generally "custom_id" is an invalid keyword.
I wanted that to setup each dropdown option to be correlated to a different modal. Is there a way to do that as I suppose custom_id doesnt work or is there a different keyword to be used?
!code send your whole code
What do you mean by generally "custom_id" is an invalid keyword
custom IDs in the context of discord's API are only to identify a single component within a message, i.e. a button or select menu; for identifying which options were selected, you'd use the value= kwarg within SelectOption and the Select.values attribute to see which ones were picked
!d discord.ui.Select.values
property values```
A list of values that have been selected by the user.
hmm that is pretty lacking of an explanation
lol okay, thank you.
Do you also know how I could setup the if statement? I did interaction.value but the attribute isn't valid.
class Inviter(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Staff", value="staff"),
discord.SelectOption(label="Player", value="player"),
discord.SelectOption(label="Studios", value="studios"),
discord.SelectOption(label="Content Creator", value="content")
]
super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
async def callback(self, interaction: discord.Interaction):
channel = vini.get_channel(1123456106740584528)
guild = vini.get_guild(1123453068952993802)
if interaction.value == "staff":
modal1 = staff_modal()
await interaction.response.send_modal(modal1)
await modal1.wait()
elif interaction.value == "player":
modal3 = player_modal()
await interaction.response.send_modal(modal3)
await modal3.wait()
etc...
values (plural) is an attribute of the Select class which returns a list, and since you're inside a method of a Select subclass you should write self.values[0] to retrieve the first value
Hello
from discord.ext import commands import discord from colorama import Fore from keep_alive import keep_alive from os import environ import json bot = commands.Bot("!", self_bot=True) # Defining bot. @bot.event # Turning the bot online. async def on_ready(): print("This program has logged in to the account " + Fore.YELLOW + f"{bot.user}.\n") with open("data.json", "r") as f: data = json.load(f) if data["guild"] == None or data["channel"] == None: pass else: try: voice_channel = discord.utils.get(bot.get_guild(int(data["guild"])).channels, id = int(data["channel"])) await voice_channel.connect() print(f"{Fore.GREEN}[-]{Fore.WHITE} Connected to {Fore.CYAN}{voice_channel} {Fore.WHITE}in {Fore.CYAN}{voice_channel.guild}{Fore.WHITE}.") except: print(f"{Fore.RED} [ - ] Error Occured. Please reconnect using commands.") @bot.command() # Join command. async def join(ctx, voice_channel : discord.VoiceChannel): await voice_channel.connect() data = {"guild":str(ctx.guild.id),"channel":str(voice_channel.id)} with open("data.json", "w") as f: json.dump(data, f) print(f"{Fore.GREEN}[-]{Fore.WHITE} Connected to {Fore.CYAN}{voice_channel} {Fore.WHITE}in {Fore.CYAN}{voice_channel.guild}{Fore.WHITE}.") await ctx.message.delete() @bot.command() # Leave command. async def leave(ctx): voice_client = ctx.message.guild.voice_client await voice_client.disconnect() with open("data.json", "w") as f: json.dump({"guild":None,"channel":None}, f) print(f"{Fore.RED}[-]{Fore.WHITE} Disconnected from {Fore.CYAN}{voice_client.channel}{Fore.WHITE} in {Fore.CYAN}{ctx.message.guild}{Fore.WHITE}.") await ctx.message.delete() keep_alive() bot.run(environ["token"], bot=False) # Run the bot by adding your token in between the quotes.`````
how would i use dicts for storing information about users who left and joined a VC?
Can anyone explain to me how this works? Its a script that keeps your discord account in a voice call 24/7 but I am confused as to how it would bypass the afk feature
any script that logs into a user account is against discord's ToS and can get your account terminated
I understand the risk with selfbots, just curious as to how the code works
hmm it might still be against rule 5 to ask specifically how a user account can prevent AFKing via automation, perhaps for a bot that would be fine (although im not familiar with it since i dont use vc bots)
this is a bit too vague as there's a lot of ways to use a dictionary, but for a simple bot a global variable is probably fine, for example: ```py
Storing voice channel ID -> number of joins
voice_join_counts = {}
bot = commands.Bot(...)
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_voice_state_update
@bot.event
async def on_voice_state_update(member: discord.Member, before: discord.VoiceState, after: discord.VoiceState):
if before.channel is None and after.channel is not None:
channel_id = after.channel.id
current = voice_join_counts.get(channel_id, 0)
voice_join_counts[channel_id] = current + 1``` note of course that the dictionary will be lost once your bot restarts
im trying to have it to when a user joins an empty VC, they can lock and unlock it. Others lose access. the user that joined after has access once the first person left. would this work with that code or does it need to be completely different?
also do you have any links/docs about dicts?
if by restricting access you mean modifying the channel permissions to disallow people from joining you could probably do that without a dictionary, although i think this might be limited by discord's strict channel edit ratelimits
i tried something like this but don't know how i would make it to where only one person can use the command
async def unlock(self, interaction:discord.Interaction):
if interaction.user.voice is None:
await interaction.response.send_message(content='You are not in a voice channel.')
channel = interaction.user.voice.channel
overwrite = channel.overwrites_for(interaction.guild.default_role)
overwrite.connect = True
await channel.set_permissions(interaction.guild.default_role, overwrite=overwrite)
await interaction.response.send_message(content='VC has ben unlocked, members can now join the VC.')```
But I can already see that going bad
u can create your custom check
or you can use the checks already availabe
What's the error?
Hi, can someone help me. I have a problem with the select menus, only the first one works and the second one doesn't even give an error, only 'This interaction failed' .
check your values in the select menu u have desc while in the callback you are checking for decs
hey sir u free at moment
so i am facing a strange issue
i was testing my discord bot
and it workd fine
then i added it to the server where it need to do that job
and suddnly it stopd responding
and now even if i change the tokens
its not respondign
@turbid condor can u help pls
well it was working fine a moment ago
so i can say that yes ti has perms
I set up a discord bot on my friends computer, when use the /command on my discord account on my pc, the command works fine. When my friend uses the command on his phone it works fine. But if he does the command on his computer where the bot is set up, the command doesnt respond and I get this error in the CMD
discord.app_commands.errors.CommandInvokeError: Command 'usernames' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
any idea why?
intents is set to all
can you show your code for usernames command
and enabled in dev portal
and 1 more question did the bot worked after joining the guild it was supposed to be used in
no it stoped after that
it was working fine in testing guild
and is it not even working in testing guild now?
yess
try making a new bot in dev portal and use its token and check
# LIST OF USERNAMES
@app_commands.command(name = "usernames", description="A List of PS4 Users & Folder ID's")
async def usernames(self, interaction: discord.Interaction) -> None:
# READ DEFAULT VALUES
with open(default_config, 'r') as f:
ftpinfoBIG = f.read().splitlines()
default_ip = ftpinfoBIG[10].replace(' ', '').replace('IP=', '')
default_port = int(ftpinfoBIG[12].replace(' ', '').replace('Port=', ''))
#CONNECT TO PS4
ftp = FTP()
ftp.connect(default_ip, default_port)
ftp.login()
ftp.cwd("/user/home/")
data = []
ftp.dir(data.append)
# LIST OF USERS
embed = discord.Embed(title=f"📑 __**LIST OF USER FOLDER ID'S**__", color=discord.Color.gold())
embed.set_author(name= f'Thank you {interaction.user.name} calling list', icon_url= interaction.user.avatar)
x = 1
for line in data:
# SKIP FIRST THREE DIRECTORY LISTINGS
if x > 2:
y = x - 2
folderids = line.split(" ")[-1]
ftp.cwd('/user/home/' + folderids)
ftp.retrbinary("RETR " + 'username.dat' ,open('username.dat', 'wb').write)
with open('username.dat', 'r') as moredetailsLOL:
text_folderids = moredetailsLOL.read().rstrip('\x00')
text_folderids = text_folderids.split(" ")[-1]
silentremove('username.dat')
embed.add_field(name = str(y) + ") " + f'__{text_folderids}__' + ' = ' + f'**{folderids}**', value = '\u200b', inline=False)
x += 1
embed.set_footer(text="Type /guide to see a list of features and commands available.")
await interaction.response.send_message(embed=embed, ephemeral=False)
ftp.quit()
i tried it too but let me do it again
defer this command
so await interaction.response.defer() by itself in the beginning or middle of the code?
then `await interaction.followup.send for the final embed message?
after your async
pefect ig?
I think I tried that and the bot stayed thinking forever but I will try again
and then change the interaction.response.send_message('.....') to interaction.followup.send('....')
it workd
wait
let me try it in test server i tried it in 3rd server
@turbid condor a sample code is working fine
on which bot the actual one or the new one you created?
new one
but not if i apply the code it suppse to do task of
can you send the code and would u make a forum of this as it might get a bit long
the actual code right?
yes
oke give me a moment
https://paste.pythondiscord.com/SMK3W#1L33
look at this line
also you assign callback after you send the message
fact, i found another solution but tysm @slate swan
how can i make it delete both mine and the bot message ? With this it does not happen.
await interaction.response.delete()
await message.delete()
@turbid condor
what is message here?
we mean where u defined message in your command?
something like that
what is message = ?? inside your code
await interaction.channel.send('Please enter a title')
message = await bot.wait_for('message', check=lambda m: m.author == interaction.user)
self.title = message.content
await interaction.response.delete()
await message.delete()```
@turbid condor
ok so this deletes your message?
Yes, delete it, but I want the bot too.
so assign a variable to the bot response and then delete it using the same way you deleted yours
if message.author == """{your id / bot's id""" :
await message.delete(1)
Try this 🙏
No
?
if message.author.id == 123456789:
# blah
yeah my bad
can someone help me, in the slash command there is a channel: discord.Textchannel, I want to take it and go to the class and send the embed where the channel is given.
@turbid condor
@tall temple
Set the channel as an attribute in the _init_ then and use it when you need to send the embed
can you put it for me I don't know where
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
timestamp kwarg
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
str.join (here name list)?
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
a, c, b
embed does not have .join method
its for string like i said
then you can pass it to embed description or elsewhere
Where do I put that?
read two messages below that
Only description?
I can't Paste In Add.failed
Look error
!code
emm.add_field(name="Below answers cup: ", value=f"{random_cups.join(random_cups)}", inline=False)
Here
cause you did it on list i told you its string method
||repr(mylist)[1:-1]||
Does this look good?
# Get the list of member IDs in team 1 and team 2
team_1_member_ids = [user['member'].id for user in team_1]
team_2_member_ids = [user['member'].id for user in team_2]
# Update the last_activity field for all users in team 1 and team 2
await collection.update_many(
{"discord_id": {"$in": team_1_member_ids + team_2_member_ids}},
{"$set": {"last_activity": datetime.datetime.now()}}
)```
Looping twice and concatenate, seems inefficient
using .bulk_write could be better here
team_1_member_ids = [user['member'].id for user in team_1]
team_2_member_ids = [user['member'].id for user in team_2]
``` also this can be just this ```py
team_member_ids = [user['member'].id for user in team_1 + team_2]
!d itertools.chain me when
itertools.chain(*iterables)```
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:
```py
def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables:
for element in it:
yield element
importing other library 
Something like this?
team_member_ids = [user['member'].id for user in team_1 + team_2]
update_operations = [
UpdateOne({"discord_id": member_id}, {"$set": {"last_activity": datetime.datetime.now()}})
for member_id in team_member_ids
]
await collection.bulk_write(update_operations)```
why create UpdateOne for each memberid when you can just do UpdateMany
await collection.bulk_write([
UpdateMany(
{"discord_id": {"$in": team_member_ids}},
{"$set": {"last_activity": datetime.datetime.now()}}
)
])
``` something about that
But more efficient 🐈
Do you know why I'm getting: Unresolved reference 'UpdateMany' 🤔
cause you did not import it
!d pymongo.collection.Collection.bulk_write
bulk_write(requests: Sequence[_WriteOp[_DocumentType]], ordered: bool = True, bypass_document_validation: bool = False, session: ClientSession | None = None, ...) → BulkWriteResult```
Send a batch of write operations to the server.
Requests are passed as a list of write operation instances ( [`InsertOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.InsertOne "pymongo.operations.InsertOne"), [`UpdateOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.UpdateOne "pymongo.operations.UpdateOne"), [`UpdateMany`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.UpdateMany "pymongo.operations.UpdateMany"), [`ReplaceOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.ReplaceOne "pymongo.operations.ReplaceOne"), [`DeleteOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.DeleteOne "pymongo.operations.DeleteOne"), or [`DeleteMany`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.DeleteMany "pymongo.operations.DeleteMany")).
from pymongo import ReturnDocument from motor.motor_asyncio import AsyncIOMotorClient
Yeah you are right
!d pymongo.operations.UpdateMany
class pymongo.operations.UpdateMany(filter: Mapping[str, Any], update: Mapping[str, Any] | Sequence[Mapping[str, Any]], upsert: bool = False, ...)```
Create an UpdateMany instance.
For use with [`bulk_write()`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write "pymongo.collection.Collection.bulk_write").
This should be enough or do I need to add it as a class as well?
from pymongo import ReturnDocument, UpdateMany
try
Thanks
https://paste.pythondiscord.com/JVFKC
Why doesnt my code work:
- Avater (Welcome Message doesnt work)
- Ticket Embed doesnt work
what does doesnt work mean??
which command
Just look at the code lol
well actually none of your commands will work cause you did not enable message_content intent
you have more commands than that
OMG
Like this right?
But if i want to start it then comes this message in console:
How?
pip install --update discord.py?
I have a problem: No matter wich video I try to play in discord with my music bot, I get the following error: [out#0/s16le @ 0000024d6f171180] Output file does not contain any stream I've already looked it up on the internet but I can't find any working solution.
(--update can be shortened to -U)
Show code maybe
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
who said they get it from youtube
they just uploaded the code
and then deleted
okay then
i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once
yo
mind helping me so it doesnt send the welcome message even tho there isnt any errors and yes it is the correct channel
@bot.event
async def on_member_join(member):
channel = member.guild.system_channel
background = Editor("Pic2.jpg")
profile_image = await load_image_async(str(member.avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white", stroke_width=5)
background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
file = File(fp=background.image_bytes, filename="pic2.jpg")
await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name} For More Information go to #✗︱rules**")
await channel.send(file=file)
Try debugging it and see if it actually works or not
Can u put this in a codeblock
async def on_member_join(member):
channel = member.guild.system_channel
background = Editor("Pic2.jpg")
profile_image = await load_image_async(str(member.avatar.url))
profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")
background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white", stroke_width=5)
background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
file = File(fp=background.image_bytes, filename="pic2.jpg")
await channel.send(f"Hello {member.mention}! Welcome to {member.guild.name} For More Information go to #✗︱rules")
await channel.send(file=file)```
There
!d discord.Intents.members
Whether guild member related events are enabled.
This corresponds to the following events...
Do you have this intent enabled
An intent
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
This requires Intents.members to be enabled.
so how do i enabel it 💀
but it worked fine when i first coded it
how do I do the
ctx.guild.region
its not working for me like it has been changed, it works last time I opened the bot
You mean it's only working once for you?
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()
!d discord.Guild.preferred_locale
The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
Changed in version 2.0: This field is now an enum instead of a str.
no like i used it before and it worked now it doesnt idk why
ok ok thanks
Welp that's what you get for copying a code from yt
lmao i didnt copy code lol
I'm 100% percent you did
well i am 100% i didnt
Welp that aside
.all() enables all intents so you have it
ye ik but idk why it doesnt work
Try restarting your bot and see if it works
did you try debuggin it?
like see if it even runs
ye it does run
well then it could be many things
for example .system_channel is optional i belive
i did nth
but my godbye msg works perfectly fine
!d discord.Guild.system_channel
property system_channel```
Returns the guild’s channel used for system messages.
If no channel is set, then this returns `None`.
It isn't printing anything in console too?
you have any other on_member_join event defined else in your code?
it does print
lemme chek
(or an error handler eating up the errors)
Can you show us if it's printing an error?
oh shi i do
Zzz
using @bot.event you can have only one registered
use @bot.listen() instead
i forgot i had this @bot.event async def on_member_join(member): guild = member.guild role = discord.utils.get(guild.roles, name='👑 Pirates 👑') if role is not None: await member.add_roles(role)

also using @bot.listen() you can pass event name into decorator and name function other name
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
ah ok ok
so i did the @bot.listen() on like every line i had the @bot.event() on
if you meant @bot.event (without the ()) then should be good
finally i am good
yea mb
put a print statement inside
thanks for the help yall
and see it you get it in console
What even is asyncio.async
I think i asked him to debug

i belive by debugging he wanted you to put some print statements inside and see which varriable holds what so you can get more in depth what is going on
Your code is inefficient. discord.utils.get is far less efficient than using Guild.get_role. Instead of finding the role each time, store the role id of the specific role and get it using get_role
so most possible case: you did not load the cog
huh
but i cant help rn hope others will
Btw no need to process commands in a listener
well i did make it work so i am done with that ima move on code smt else
It's a listener not an event
What do you mean load the event
Listener already handles the process command for you
In your cog put this
async def on_cog_load(self):
print('loaded')```
Inside the listener
Inside the listener??
as a listener
At the end of this code
Wrong ping
Just make sure it's aligned with your async def on_message
Who isn't
@slate swanwhat's your issue
His listener isn't firing
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
print("test")
if message.author != self.bot.user or not message.author.bot and message.mentions and message.type != discord.MessageType.reply:
async with self.bot.pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
for mention in message.mentions:
await cursor.execute("SELECT emojitag, emojiID FROM auto_react WHERE guildID=%s AND targetID=%s;", (message.guild.id, mention.id))
fetch: tuple[dict] | None = await cursor.fetchall()
for emoji in fetch:
await message.add_reaction("<:{}:{}>".format(emoji["emojitag"], emoji["emojiID"]))
async def on_cog_load():
print('loaded')
if message.author != self.bot.user or not message.author.bot and message.mentions and message.type != discord.MessageType.reply: what is your intention with this conditional statement
Not even loaded?
Is it even a valid listener/event
Nvm i forgot to put self
!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.
Mb it was cog_load not on_cog_load
@client.command(aliases=['user', 'userinfo'])
async def info(ctx, user: discord.Member):
"""Gets info on a member, such as their ID."""
embed = discord.Embed(title="User profile: " + user.name, colour=user.colour)
embed.set_image(url = user.banner)
embed.add_field(name="Name:", value=user.name)
embed.add_field(name="ID:", value=user.id)
embed.add_field(name="Status:", value=user.status)
embed.add_field(name="Highest role:", value=user.top_role)
embed.add_field(name="Joined:", value=user.joined_at)
embed.set_thumbnail(url=user.avatar)
await ctx.send(embed=embed)
ok I need help, its not showing the user's banner, aswell as how to do the new Client.fetch_user thing
Nah it's cog_load i just checked my github repo and docs
Try user.banner_url
ok ok
object has no attribute
actually, you're correct. This is not an event, so it does not need to be declared an event.
class discord.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN asset’s URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
Check what attributes it has
hmmm
Also banner is optional it could be that user Has no banner
You need to check if it exists
because the set_image for an embed requires URL
Did you check Asset docs i linked?
Ill try asset.url etc...
@slate swan
You use discord or disnake?
I use nextcord
No one use Discord
I used disnake
Cool 
Because Disnake Very easy
Welp I'd get some sleep I'm messing up too much now
ok Im so confused, how do I put the banner image/gif into the embed
someone spoonfeed me xd
When you learn it, you get addicted. Programming is like that
Im so lost
pls can you give me some advice
Disnake or discird?
Alright waite
!rule 10
Oh
Lmao

so what I learned so far is banner is an asset
and that it requires await fetch user?
BRUHHH
!d discord.Member.banner
Yeah it will be none if the user doesn't have a banner
!d discord.User.banner
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
Right
I tried that but it doesnt work
I used disnake I can't help you
maybe its because the user is using a GIF?
You need to fetch the user/member to access their banners
Nope shouldn't be a problem
In discord.py v2.0 you can use
You may have to re-fetch the user for the banner to work properly
banner_url = user.banner.url ```
does anyone know how i would input the data that has been inputted into a modal into a database but the modal has been answered multiple times?
Stop using gpt
That's old
I am making an image profile command. I would like to access the member's banner for this. Is there any way we can do that in discord.py?
If it is not clear what i mean by banner then, the image w...
Not ChatGBT
Still old
I am not use chat gpt
It's still correct, so it's probably fine
I helped him
You spoonfed them
any ideas?
Which you shouldn't
In user_id: Value "n3srei" is not snowflake.
anyone know how to fix this kind of error?
what is a snowflake
@client.command(aliases=['user', 'userinfo'])
async def info(ctx, user: discord.Member):
Userdiscord = await client.fetch_user(user)
"""Gets info on a member, such as their ID."""
embed = discord.Embed(title="User profile: " + user.name, colour=user.colour)
embed.set_image(url = Userdiscord.banner)
embed.add_field(name="Name:", value=user.name)
embed.add_field(name="ID:", value=user.id)
embed.add_field(name="Status:", value=user.status)
embed.add_field(name="Highest role:", value=user.top_role)
embed.add_field(name="Joined:", value=user.joined_at)
embed.set_thumbnail(url=user.avatar)
await ctx.send(embed=embed)
Tbh just store the entry with index no
wdym?
U need to put user.id
That's not helping that's spoonfeeding and you may be punished for this here
ah
Is it?
Like instead of the user_id as a key value use an index to make enteries
in the database?
Where else are you storing the submissions?
nowhere
i’m just really confused as to how i’d store the data if the modal has been answered more than once by the same user
I literally told you just now
overwrite or append the db
Yeah and not spoonfeeding server
Yes you right
but how do i append to a databse
what db are you using?
mysql
Hi
do i do cursor.execute(sql, data)?
you can use an update statement
sql is the INSERT etc etc