#discord-bots
1 messages · Page 323 of 1
What's the error
Traceback (most recent call last):
File "/home/gaelg/Desktop/xtreme-main/xtreme.py", line 28, in <module>
conn = mysql.connector.connect(
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/init.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 95, in init
self.connect(**kwargs)
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 716, in connect
self._open_connection()
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 208, in _open_connection
self._do_auth(self._user, self._password,
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 144, in _do_auth
self._auth_switch_request(username, password)
File "/home/gaelg/.local/lib/python3.10/site-packages/mysql/connector/connection.py", line 177, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'u79588_E6O83yeRrg'@'172.58.166.30' (using password: YES)
Does interaction.edit_original_response() attachments arg have a maximum amount
try it and see
Yeah I think it's 10
Okay, so test it then
How could I added attachments to this pagination?
KEYS_PER_PAGE = 10
pages = []
for chunked_files in more_itertools.chunked(files, KEYS_PER_PAGE):
embed = discord.Embed(
url=url,
title=f"Downloaded {index} files.",
description=new_desc,
color=discord.Color.green(),
).set_author(name=username, url=f"https://www.instagram.com/{username}/").set_footer(
text=f"👍 {likes} • 💬 {comments}"
)
pages.append(embed)
await Paginator.Simple(timeout=60).start(interaction, pages=pages)
tengo un problema
!rule 4 🫠
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
async def edit_footer(self, interaction: Interaction) -> None:
"""This method edits the embed's footer (text, icon_url)"""
modal = ModalInput(title="Edit Embed Footer")
modal.add_item(
TextInput(
label="Footer Text",
max_length=255,
required=False,
default=self.embed.footer.text,
placeholder="Text you want to display on embed footer",
)
)
modal.add_item(
TextInput(
label="Footer Icon",
required=False,
default=self.embed.footer.icon_url,
placeholder="Icon you want to display on embed footer",
)
)
modal.add_item(
TextInput(
label="Include Timestamp (True/False)",
max_length=5,
required=False,
default="True",
placeholder="True or False",
)
)
await interaction.response.send_modal(modal)
await modal.wait()
self.embed.set_footer(
text=str(modal.children[0]), icon_url=str(modal.children[1])
)
include_timestamp = str(modal.children[2]).lower() == "true"
if include_timestamp:
self.embed.timestamp = discord.utils.utcnow()
else:
self.embed.timestamp = None```
can someone tell me why if True the timestamp doesnt set?
If you print include_timestamp is it True or False?
let me test
A modal also isn't great for True/False inputs
Include Timestamp: True
Setting timestamp.
Include Timestamp: False
Not setting timestamp.
Why are you showing 2 outputs?
Show you what it does for Both True or False
I know what it'll do, I'm just saying it's not a good format overall
What if somebody says yes instead of True?
Average Discord user is
it states what to put 😭
Most users don't read carefully
If they dont read, then its on them tbh
They'll see include timestamp and act accordingly
Well, thats on them, im just trying to fix the issue :/
"label="Include Timestamp (True/False)","
also says it twice, so theres no way they miss it :)
I just showed you that it does?
You showed 2 outputs
So which is it
It cannot be both True and False at the same time
If Include Timestamp: True then setting timestamp if False, Not setting timestamp..?
Thats if you put True or False..?
If you print include_timestamp is it
TrueorFalse?
oh, hold on
Wait, im confused, its gonna go off of what the user inputs?
include_timestamp is set off the user input. You're having an issue where even if the user enters true then it's still not setting. Therefore, you need to pass the true value and print include_timestamp
anyone know?
You have to assume that users will find every way to break/abuse your program.
And handle such scenarios accordingly
Collecting git+https://github.com/RejectModderss/dispie (from -r requirements.txt (line 9))
Cloning https://github.com/RejectModderss/dispie to /tmp/pip-req-build-iz8wec4o
Running command git clone --filter=blob:none --quiet https://github.com/RejectModderss/dispie /tmp/pip-req-build-iz8wec4o
error: unable to write file Lavalink.jar
error: unable to write file README.md
error: unable to write file __pycache__/embed_options.cpython-38.pyc
error: unable to write file application.yml
error: unable to write file dispie/__init__.py
error: unable to write file dispie/embed_creator/__init__.py
error: unable to write file dispie/embed_creator/__pycache__/__init__.cpython-38.pyc
error: unable to write file dispie/embed_creator/__pycache__/base.cpython-38.pyc
error: unable to write file dispie/embed_creator/__pycache__/methods.cpython-38.pyc
error: unable to write file dispie/embed_creator/methods.py
error: unable to write file dispie/help_commands/__init__.py
error: unable to write file dispie/help_commands/__pycache__/__init__.cpython-38.pyc
error: unable to write file dispie/help_commands/__pycache__/minimal.cpython-38.pyc
error: unable to write file dispie/help_commands/minimal.py
error: unable to write file dispie/music/__init__.py
error: unable to write file dispie/music/client.py
error: unable to write file dispie/music/player.py
error: unable to write file dispie/music/types.py
error: unable to write file dispie/paginator/__init__.py
error: unable to write file dispie/paginator/__pycache__/__init__.cpython-38.pyc
error: unable to write file dispie/utils/__init__.py
error: unable to write file dispie/utils/__pycache__/__init__.cpython-38.pyc
error: unable to write file dispie/utils/__pycache__/input.cpython-38.pyc
error: unable to write file dispie/utils/input.py
error: unable to write file examples/embed_creator/command.py
error: unable to write file examples/embed_creator/embed_options.py
error: unable to write file examples/pagination.py
error: unable to write file logs/spring.log
error: unable to write file logs/spring.log.2023-03-06.0.gz
error: unable to write file main.py
error: unable to write file requirements.txt
error: unable to write file setup.py
error: unable to write file tcwalther.cython-0.1.0.vsix
fatal: unable to checkout working tree
warning: Clone succeeded, but checkout failed.
You can inspect what was checked out with 'git status'
and retry with 'git restore --source=HEAD :/'
error: subprocess-exited-with-error
× git clone --filter=blob:none --quiet https://github.com/RejectModderss/dispie /tmp/pip-req-build-iz8wec4o did not run successfully.
│ exit code: 128
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× git clone --filter=blob:none --quiet https://github.com/RejectModderss/dispie /tmp/pip-req-build-iz8wec4o did not run successfully.
│ exit code: 128
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.```
Can someone tell me why it does this?
i just need help fixing it..
what's your python version
u would have to make your custom pagination system which handles attachments
a simple format could be {embed: attachment, embed1: ...}
I'm using this https://github.com/soosBot-com/Pagination I think it's capable already?
lemme take a look
it doesn't handle attachments
So there's no hacky way to do it besides editing the package
its barely a package it's just a single file
i suggest you just make your own
its pretty easy to make one
I already use that package for the rest of my commands 
subclass it then
3.11
well thats what the server is running
On my IDE it worked fine which is 3.10.5
but i thought it would work for 3.11 too?
it should
can u link the source ur installing from
Source?
🚀 A fantastic library created for use with Discord.py - GitHub - RejectModderss/dispie: 🚀 A fantastic library created for use with Discord.py
that?
I think its more of the host... because my friend could clone it, an i can clone it... i will have to talk to my Manager about it so he can fix it.
My friend owns the Host, so I will need him to look into it I think..
read the error, you too cloned it successfully
Yes i know it cloned it, but it isnt able to write to it
Which is a host error, not a github or anything else, just a host error 99% sure
Make sure you ain't cloning it into already existing git repo
Also please run ls -ld .. in the dir you are running git in and show the output
just -a would be enough
How to run discord bots 24/7 for free in replit?
Replit isn’t a host and shouldn’t be used as one
replit is a host anyway
It’s definitely not
Nuh uh
Why would a host require you to setup a web server alongside your main application and ping it every 30s to prevent replit from disconnecting it?
That’s not normal
Keep alive is a workaround to a prevent replit created
I could make a ping spam bot
😂
That doesn’t make replit a valid host
And I don't care
You should. Most people aren’t going to help you “setup” replit for hosting
😂 😂
You're the only one being anyhwere near rude.
I didn't do anything💀
I assume you're a little kid, maturity must be new to you.
You're not mature.
Yeah and?
Ok can we just stop ur kinda getting off topic
@patent lark If ur assuming I'm a lil kid them how old are you?
Bro why is the text like that
Can you stop? You're getting off topic.
This channel is for discord.py help (or other related libs). If you would like to speak on another topic. please find the perferred channel. or an ot.
!ot
Please read our off-topic etiquette before participating in conversations.
Ok
Bro said replit 😭
😂
Ain't no way drama in #discord-bots !
😭
That was my first text bro
Replit drama
did you not just see the drama...?
Idk I just came
That was my only text 😭
I'm leaving this server this server doesn't respect me
That's just one person, the regulars are okay
If you read the above messages, you've succeeded to disrespect anyone you've spoken with so far.
I would agree with this statement
Except me ofc
All you have done is be rude and disrespect anyone who said anything to you.
Okay what do you mean? Im not a github nerd... i only use github to keep my source safe and to copy packages and make them custom...
ive only used github for like 3 weeks now 😭
Do you have ssh access to that host
💀
Thats crazy 😭
Anyways do you
I have full access on the host yes
@vapid parcel we don't need to repost that. Moderators have handled it.
<@&831776746206265384>
Ty
Oop
Can you run the command I mentioned @vapid parcel
Sorry for the ping.
what command?
I didnt know it was handled
can you please change your nickname to something not invisible/unclickable?
Sure.
Moderators reacted within a fraction of a second
There we go
ls -ld ..
Facts tho 😭
thanks, appreciate it
👍
Yeah in your directory that you are trying to run git
Yeah
it does nothing,..
Well it should give output
Into stdout or stderr idk for sure
I don't think you can submit commands while it runs
So turn it off?
Im just going with what i have
cant really complain, this host is free because my friend lets me use it...
plus im poor, so no complaining here :)
But yeah, still not working...? the command doesnt work while off either.
It should give output like this
@vapid parcel @vale wing i think its a pterodactyl panel, it doesnt allow user commands
its just made to host specific stuff, nothing more
does it look like this?
could you show the settings?
Would show the server address
oh then
Mine is just custom, but yea.
the owner of the server yes
Damn okay
Well thats my manager, so we will just wait for him to respond ig
idk
who knows 😭
@vale wing
welp what does this command do
we will just have to do it manually. its a Docker (i have NO clue what that means)
Shows directory permissions
Docker is containerization service which is pretty cool
I cannot say for sure
Investigating this without direct access will be a pain
:/
Well why does 1 git work, but the other doesnt?
that means the host supports the git? idk man im just really lost on what the damn issue is...
Is git run outside of docker or inside
imma be real, i have no clue, all i know is that i goes through the requirements, which its inside of requirements then it starts installing everything inside of requirements
what if i put the git inside of the startup command?
Well I lost my mobile ssd so I think that it may be a nice time to try other libary to rewrite my bot. I thought of my trying disnake but bot sure about that. What do you think about these libary?
I used to code on d.py
Just use discord.py
i mean discord.py is pretty much the best one to me: its very well documentated and literally 90% of the python discord bot coders are using it hence why many people can help with it
More than 90%
Downloads Last Month:
- discord.py: 6,800,000
- pycord: 17,000
- nextcord: 150,000
- disnake: 55,000
- interactions.py: 850
Not to mention the amount of git clones of the discord.py repository for the master build
real
The majority
oooookay...
i only use mainly discord.py for my bots and i use interactions.py to add slash command interactions in those d.py bots
interactions.py is an extremely outdated and deprecated library
discord.py natively supports app commands, and has for a long time
idk im not sure which one i use but it has something to do with interactions
im relatively sure i used to use int.py for one of them before i swapped it
All of those slash command extension libraries are deprecated as 99% of people removed them when discord.py added slash command support
Discord.py only Has so many downloads cause its assumed being "main" library
For me personally i find nextcord and disnake the best
For which reasons
interactions.py is a maintained and standalone library since their release of v4.0 <t:1639509540:R>, about 8 months before dpy 2.0 released, so really they were first in comparison
though goose's statement maybe implies they were using <=3.0.3? back when it used to be called discord-py-slash-command and imported as discord_slash, that or goose meant they were running both libraries alongside each other which is... definitely a way to do it
Last push was 2 months ago so extremely outdated was probably a stretch on my part
you're looking at the stable branch, PRs go to unstable
so their last activity was a few days ago
Oh I didn’t even know it’s still active
I’ve actually never seen anybody use that library surprisingly
hmm yeah, i guess their discord would be a better place to ask
hi. i need some help with code
how do i add arguments to the @tree.command()?
from discord import app_commands
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@tree.command(name = "initiate", description = "Initiate the PyGoose command g4-sAB.GXC")
async def initiate(interaction):
commandname = "g4-sAB.GXC"
await interaction.response.send_message(f"`initiated {commandname}.`")
Same way as prefixed commands. You just add them as function parameters
i dont quite get it can u give an example
You add arguments to your function with typehints. Those'll then be converted to arguments for your slash command
like how can you show me?
i want to use it with the options argument for the @tree.command() thing
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
Which options are you talking about?
There's options for select menus, but not slash commands
How do I set a command to bot owner only again? lol
A slash command or prefixed
slash
I forgot and cbf finding a bot that has owner only lol
too many discord bots ;-;
You'd have to manually check it iirc
commands
You can do it with an if statement in the command or a decorator with app_commands.check
It's legitimately like 2-3 lines of code required
ya
like how, do i declare them as variables like this?
@tree.command(name="test", description="idk ig this is a test", cmdtype = str)
async def test(interaction):
#rest goes here...
No
You can see there's no cmdtype here
You can use
psh
uh
no, as in my variable is cmdtype. how can i declare one like that?
ty @final iron
!d discord.ext.commands.Bot.is_owner
await is_owner(user, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Checks if a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) or [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) is the owner of this bot.
If an [`owner_id`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.owner_id) is not set, it is fetched automatically through the use of [`application_info()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.application_info).
Changed in version 1.3: The function also checks if the application is team-owned if [`owner_ids`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.owner_ids) is not set.
Changed in version 2.0: `user` parameter is now positional-only.
Changed in version 2.4: This function now respects the team member roles if the bot is team-owned. In order to be considered an owner, they must be either an admin or a developer.
You can call that, and return it
i want the user to input an option into a variable of str type and then it returns something specific if it has a value of something
You would create an argument in the function named cmdtype and type annotate it to a str
alr so im trying to import things
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
i have everything installed but for what ever reson it says no modual named discord_slash import SlashCommand
discord.py has natively supported slash commands for 2 years
There's no reason to use a 3rd party library
oh ._.
then how do i get it when i press / to have stuff pop up?
what do i use to replace it?
For the gist, I know it's long but please read the entire thing. I've had many people ask questions which are answered later in the page
alr thx
I'm willing to breakdown code or further explains concepts but please just read the entire page, the first part is especially important
thanks, will ask if i need further help
else:
reply = await ctx.reply(f"Clearing warnings from {member.mention}...", ephemeral=True)
await self.bot.db_connection.execute("DELETE FROM warnings WHERE user_id = ? AND guild_id = ?", (member.id, ctx.guild.id))
await self.bot.db_connection.commit()
success_embed = discord.Embed(
title="Warnings Cleared",
description=f"{warning_count[0]} warnings for {member.mention} have been cleared.",
timestamp=discord.utils.utcnow(),
color=config.main_color
)
success_embed.add_field(name="Reason", value=reason, inline=False)
success_embed.set_author(name=f"By: {ctx.author.display_name}", icon_url=ctx.author.avatar.url)
success_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await ctx.send(embed=success_embed)
await reply.delete()```
this works the same as ctx.send... correct?
What works the same?
Sure
Okay, just making sure
Wait, no
Yes, yes
You'd already be responding to the user with the ctx.send if the command was an interaction
Im wondering, does ctx.reply do the same thing
No
so it has to be ctx.send
You'd just create another message to reply
Yes
So reply doesnt accept interaction, thats all i needed 😭
using guild to create a text channel wont work within subcommands :?
or is there an issue somewhere else i keep getting the error that bot doesnt have id
Can you send the error?
Oh yes, bot instances doesn't have ids, but its account does
You can get the bot's account (or user) instance from the bot.user attribute
ah says clientUser doesnt have the attribute create text channel either
Because it doesn't. Maybe I should have explained it better
Are you trying to create a channel with a permission overwrite for the bot?
wait
i think i understand now
yes oh my gosh i cant believe such a long headache was so simple
i am silly thank u!! @naive briar
Don't worry about it 
How can we get discord user about me content in discord.py 1.7.3 version
You cannot. Also, discord.py 1.7.3 is very outdated
Little question, if I want a user to give a value between 0 and 10 (0, 1, 2, ..., 10), what's the best thing to do:
A user text input where they send a value in chat, but I have to make sure this value is within the range?
A series of button below the question that the user has to click, so I don't have to check the value. But I repeat this button process for the series of question the bot asks
Use slash command 
With a integer argument
I can't, it's already part of a slash command and I'm inside a if condition
Oh, then ig use chat input
I dont get a point using button anyway, it think button isnt bad either, its upto your choice
Something like create a range(10) amount of buttons with the label i and have a same callback for each then add the button to a View then use View.wait() ig its better 
Ye
Select menu maybe
!d
Pack? 
Can someone help us in #1176551390798155856
Kinda just needing help... we have no clue how to fix this in anyway.
Hey so, I'm trying to dynamically create several buttons with value between 0 and 10 so that when a user click on one of them, it sends its value in chat. I've done this so far:
class StatButtons(discord.ui.View):
def __init__(self, bot, ctx):
super().__init__()
self.ctx = ctx
self.bot = bot
def create_button(self, value):
return discord.ui.Button(label=str(value), custom_id=f'number_button_{value}')
def add_buttons(self):
for value in range(1, 11):
button = self.create_button(value)
self.add_item(button)
async def interaction_handler(self):
interaction = await self.bot.wait_for('button_click', check=self.interaction_check, timeout=self.timeout)
await self.callback(interaction.component, interaction)
await self.interaction_handler()
async def callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message(f"You clicked the button with value: {button.label}")
async def on_timeout(self) -> None:
await self.message.channel.send("Timed out")
await self.disable_all_items()
async def disable_all_items(self):
for item in self.children:
item.disabled = True
await self.message.edit(view=self)
async def interaction_check(self, interaction: discord.Interaction):
return interaction.user == self.ctx.author```
with a test command:
```python
@commands.hybrid_command(name='test', with_app_command=True)
async def test(self, ctx: CustomContext):
view = StatButtons(self.bot, ctx)
view.add_buttons()
await ctx.send("Click a button:", view=view)
await view.interaction_handler()```
But every time it gives me **THIS INTERACTION FAILED**. Is there a way to fix that?
there is no such event like button_click use button callbacks instead
wdym by that
thats how you create buttons and generally use views
I'm trying to add multiple buttons using a for loop by the way
how would you do that then
I kinda get how this works for one but when you have several like that?
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
or create a Button subclass and override the callback method
huh
I don't see any callback there either
cause they use button decorator that assigns method its decorating as callback
then do I just make the same thing expect I put a for loop in the init or somewhere else
problem is the label depends on the button pressed
so I can't just put a label in the decorator
no like i said assign callback yourself or use custom subclass
if you want dynamic you cant use button decorator
yeah I want something dynamic
custom Button subclass ^
I don't want to repeat the same button function 10 times that's kinda stupid
You can manually initialise the button class and set the callback inside your loop to dynamically create them
# Button for character statistics definition
class StatButtons(discord.ui.Button):
def __init__(self):
super().__init__(style=discord.ButtonStyle.secondary, label='\u200b')
# This function is called whenever this particular button is pressed
async def callback(self, interaction: discord.Interaction):
assert self.view is not None
view: OCStat = self.view
view.stop()
await interaction.response.send_message()
# This is our actual statistics selection View
class OCStat(discord.ui.View):
def __init__(self):
super().__init__()
for i in range(11):
self.add_item(StatButtons())
I'm trying to make sense of the example in this context
it's just how to I get the label of the button pressed in the interaction.response.send_message()
you need to get the number in button from the for loop
then the init takes label as an argument
wait and since StatButtons is an instance of discord.ui.Button I just need to do interaction.response.send_message(self.label) ?
no wayyyyyy
but if I want to store this value in a variable how would that work
examples/views/tic_tac_toe.py lines 17 to 18
self.x = x
self.y = y```
so uh, like before, simply self.label ?
class StatButtons(discord.ui.Button):
def __init__(self, label):
super().__init__(style=discord.ButtonStyle.secondary, label=label)
# This function is called whenever this particular button is pressed
async def callback(self, interaction: discord.Interaction):
assert self.view is not None
view: OCStat = self.view
view.stop()
await interaction.response.send_message(self.label)
# This is our actual statistics selection View
class OCStat(discord.ui.View):
def __init__(self):
super().__init__()
for i in range(11):
self.add_item(StatButtons(label=str(i)))```
# Example usage:
@commands.hybrid_command(name='test', with_app_command=True)
async def test(self, ctx: CustomContext):
"""Starts a counter for pressing."""
await ctx.send('Press!', view=OCStat())```
and what is the problem about it?
I want to save the label value selected when the button is clicked
not just send it in chat
you want to save it where
because I need it for later use when running a command
local variable, then to a sqlite3 database
why not just save it to database right away?
because I ask the user several question, so several times he selects buttons, saves the value and then, ONLY THEN i save everything at once in the table
wdym by that
self.view["data"] = 123
so simply self.view['data'] = self.value?
actually
i missed it
its self.view.data["somedata"] = 123
and you have to define data dictionary in view
self.view.data['somedata'] = self.value?
could be
it's easier than that
class StatButtons(discord.ui.Button):
def __init__(self, label):
super().__init__(style=discord.ButtonStyle.secondary, label=label)
self.label = label```
lmao and then access the label value like that
yeah like i didnt show you that already
.
How do I make the "/" commands actually show up when you type "/"
lmao
do you use @commands.hybrid_command(name='command_name', with_app_command=True)?
I think there is also a time where it needs to be updated in the list so give it some time
sync them
yeah but it's not an object of OCStat but of the StatButton
you use discord.py?
Yea
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
async def ticket_add(self, inter:
Interaction):
ticket_add_member_view = TicketAddMember()
await inter.response.send_message(content="Hi", view=ticket_add_member_view)```
view.py
```py
class TicketAddMember(nc.ui.UserSelect):
def __init__(self):
super().__init__(placeholder="Please select a member...", min_values=1, max_values=1)
async def callback(self, inter: Interaction):
query = BotDB().query_ticket_informations(inter.channel.id)
if query is not None and query[3] == inter.channel.id:
selected_option = self.options[0].value
print(selected_option)
members = query[2]
member_list = members if members is not None else []
if selected_option not in member_list:
member_list.append(selected_option)
# BotDB().update_ticket_add_member(inter.channel.id, member_list)
else:
pass```
Error
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 497, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 206, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 918, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\modules\ticket_system\cog.py", line 43, in ticket_add
await inter.response.send_message(content="Hi", view=ticket_add_member_view)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 880, in send_message
payload["components"] = view.to_components()
AttributeError: 'TicketAddMember' object has no attribute 'to_components'```
only views should be sent with view=, but your TicketAddMember is a UserSelect component
assuming nextcord didn't change this, a quick way to put it in a view would be: py view = nextcord.ui.View() view.add_item(SomeButtonOrSelect())
Thank you 
Anyone an idea on how to make a AI support discord bot? Like a bot who replys to users questions and problems in a ticket like a supporter
Are you looking to train your own model or use an already existing one
Ok, so, when I was making my discord bot, I decided to use a symbol "$" instead of "/", and now the only way that the new slash commands will show up is if I'm using the bot on my test server. Anyone know why?
@slate swan
yo, i need a little help. So ive created some modmail functionality, and i am grabbing the "thread channel" using discord.utils.get, looping through guild.text_channels and accessing the TextChannel.topic (which is the thread users id). I want to create a subscribe function that does the following: When a staff member runs .subscribe in the thread, it adds their ID to the topic as well, separated by a comma. And will ping them anytime the thread user sends a message. Heres my issue, when the subscribed users id is in the topic along with the thread user id, the thread channel will return None because im checking if the topic is their user id. And obviously two IDs and a comma is NOT their user id. How can i get around this?
guild.text_channels doesn't include threads. If you want to search for threads, you'd access them by text_channel.threads
!d discord.TextChannel.threads
property threads```
Returns all the threads that you can see.
New in version 2.0.
Just a double loop basically
No, im using a text_channel, not a thread channel
Im just calling it "thread channel" in my code
Who would ever be confused
Variable naming does matter
I feel like this whole implementation is convoluted but you could just split the string on “,” and loop through the indexes, or if the target ID will always be first then you can just grab the index
Anyone got an example on how to create a slash command using discord.py?
I have fixed my issue now, thanks for your suggestion
How'd I create an embed with buttons? Is there an example for that?
There’s a views folder
Which one?
And how'd I add the buttons to the embed?
The views folder lol
It’s in the example folder
counter.py is probably the simplest implementation
And is it possible to use this in my moderation class?
The buttons would be attached to the message itself so you’d pass your discord.ui.View instance into the view kwarg while sending
as for embeds you would create an instance of the discord.Embed class, set whatever attributes you want, and then send it in your message using the embed= argument
So I couldn't do embed.add_action?
the discord API doesn't have any relationship between buttons and embeds, so dpy doesn't provide a method like that
Ah
Yeah, buttons are bound to the message itself, just like embeds
Dang, alot of code to add in a button lol
Not really if you take it step by step
So in theory, could I make a file within my cogs folder called "counters.py" and just place all of the individual buttons in there and then call them onto messages when I need such as in my "moderation.py" file and then depending on the button they click, perform the rest of the actions within the "moderation.py" file?
Struggle with building the logic behind my code sometimes lol
The typical implementation for buttons is the discord.ui.button decorator is used on a function, and that function becomes the callback for the button created
Buttons can be dynamically created though
or do you mean you want your view to be reusable across multiple cogs? sure you can do that
Honestly, I have never used buttons before and slash commands so I am just trying to learn them (the wrong way, I know lol)
Are either of you able to hop into one of the VCs to explain please?
i cant, but i would recommend looking at the view documentation to see what methods are provided
Where is that located?
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
views are usually written to handle actions in the callback of each button but they do allow you to wait for the view to be stopped, at which point you can have some attribute to represent whatever selection they made
the confirm.py example shows that
import discord, json
from discord.ext import commands
# Cogs
from cogs.moderation import Moderation
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
class Client(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.moderation = Moderation(self)
async def on_ready():
try:
synced = await # commands tree sync
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="RMC play!"))
print(f'Logged in as {bot.user.name}')
@bot.event
async def on_message(message):
await bot.process_commands(message)
with open('config.json', 'r+') as f:
config = json.load(f)
bot.run(config['botkey'])
As I am going to have multiple classes, how can I cycle through them all to sync them?
err you should only have one client/bot instance
also seems unusual to be instantiating the cog manually without adding it with add_cog(), or more conventionally setting it up as an extension
That's what I was thinking but I didn't know if you could do that when using interactions/slash commands
As it works of a "tree"
the Bot class handles registering slash commands in cogs defined with @app_commands.command() for you
HELP PLEASE
- use just the commands.Bot class (it does everything discord.Client can do, and comes with a free CommandTree and prefix command support)
- have a command to sync your tree when you want to
- setup your cog as an extension so you can load it
in summary it might look like: ```py
class Bot(commands.Bot):
async def setup_hook(self):
await self.load_extension("cogs.moderation")
bot = Bot(command_prefix="!", ...)
bot.run(...) py
cogs/moderation.py
class Moderation(commands.Cog):
...
async def setup(bot):
await bot.add_cog(Moderation(bot))```
Ah, this seems a lot more efficient and has filled a void in my knowledge, thank you 💙
I think it would be easier to use a existing one right? But i have to be able to input my own data like the rules or frequently asked questions so it can really help
I created a discord bot that helps you make and find new places to get coffee. Who would like to try it?
Maybe some other icon for Duration ? User Id and Duration have same icon 
I'm making a really good bot in python passionately, looking for some team members aswell to help me make it the best visual embed bot on discord
oh yes I'm looking for one currently
👌 Ye, other than that it looks real nice
Thank you!
you seem like an experienced developer/person, just offering would you like to join the development of this bot? we have plans to publically launch it by next year jan-feb and till then we'll be working on making it a really good visual experience (the stylish embeds and informative responses rather than just saying "xyz was banned")
I can personally code this bot, but I run out of ideas so It would be nice to have a team to work with ^^
we've got one of my friends already onboard the project
I've got plenty of work myself 😅 And just getting back to Python rn from doing C# only for the past few months.. xD
yeah you don't really need to code anything tbh, just guide me on the embed/visual stuff etc
lmk if ur down, totally fine if you cannot.
I just came here to ask some peeps for advice on how to communicate to Discord bot from website and back asynchronously 😅 How do people usually do this ? Do I just run both under 1 process ? With Python running on 1 thread for most part without using multiproc it scares me lol..
I got a bot sitting in little over 100 servers with ~8K users it frequently iterates over and uh xD I was using RPyC to communicate between web process and bot process but damn is it slow xD
What/how do other big python bots do this ? xD 
Do they just store all the user-data etc.. and everything on their DB 
really depends on what you're trying to do, if you want something like an event, and your db is postgresql, you could use the pg pub/sub feature. also for a website, run them in a separate process, you would just make the frontend communicate with an api via SSE or websockets or any other IPC, and your bot could connect to that through websocket as well
Wow I do use postgres yep and I had no clue about pub/sub feature, it does look real cool tho! I'll check it out and will look into using websockets for this 👌
oke
discord client issue
oh
does your create_pool() literally have ... for the address? that seems to be implied by the Ellipsis in your error message
I need help with requests
im getting this error
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='raw.githubusercontent.com', port=443): Max retries exceeded with url: /Fraesh/vps-db/master/vpsdb.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000024A19D33B90>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))```
but i can open the API url in my browser
code:```py
import requests
json_url = 'https://raw.githubusercontent.com/Fraesh/vps-db/master/vpsdb.json'
response = requests.get(json_url)
data = response.json()
if isinstance(data, list) and data:
sample_item = data[0]
if isinstance(sample_item, dict):
keys = sample_item.keys()
print(f"Keys in each item: {keys}")
else:
print("Each item in the JSON data is not a dictionary.")
else:
print("The JSON data is either not a list or is empty.")
is the error intermittent? Could be firewall. Could be their side
also in the context of discord bots, most are async so you wouldn't want to use requests, but an async library such as aiohttp
Idk, I even turned off windows firewall but didnt work
I'm currently writing a discord bot, and I'm looking for the best way to create and categorize slash commands. Previously I've used a CommandTree, but adding parameters, descriptions, and organization (for example, command groups) was difficult and needlessly complex. So before I fall into any pitfalls, what's the best way to create a slash command structure?
class discord.ext.commands.GroupCog(*args, **kwargs)```
Represents a cog that also doubles as a parent [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group) for the application commands defined within it.
This inherits from [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog) and the options in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) also apply to this. See the [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog) documentation for methods.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of the cog.
Hybrid commands will also be added to the Group, giving the ability to categorize slash commands into groups, while keeping the prefix-style command as a root-level command.
For example...
how were you adding slash parameters/descriptions? the two different syntaxes should be fairly readable
I couldn't find anything, really.
@tree.command(name = "addassignablerole", description="Add a role to the assignable roles list")
@app_commands.describe(role = "role to add")
@app_commands.rename(role = "role")
you er don't need a rename if it's still going to be given the same name
but regardless for descriptions, Google/Sphinx/Numpy-style docstrings can be used instead: ```py
@bot.tree.command(name="add-assignable-role")
async def add_assignable_role(interaction, role: discord.Role):
"""Add a role to the assignable roles list.
:param role: The role to add.
"""```
Okay, what about grouping commands?
if you're not using cogs/extensions the first two syntaxes would be appropriate, but if you are using cogs you'd want to pick one of the last two
tbf this is stuff that should be in an official guide, but that's been WIP for over a year now
Speaking of, what's the usecase of cogs? When should I use it?
its part of the discord.ext.commands extension (to be used with commands.Bot rather than discord.Client), and it helps you organize your code in different files
for example: ```py
main.py
from discord.ext import commands
class Bot(commands.Bot):
async def setup_hook(self):
await self.load_extension("path.to.my_extension")
bot = Bot(command_prefix="?", ...)
bot.run(...) py
path/to/my_extension.py
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def some_prefix_command(self, ctx: commands.Context):
await ctx.send("Hello world!")
@app_commands.command()
async def some_slash_command(self, interaction: discord.Interaction):
await interaction.response.send_message("Hello world!")
async def setup(bot):
await bot.add_cog(MyCog(bot))```
if you want a bigger example, you can see how i organized a bunch of various features in cogs/extensions here
https://github.com/thegamecracks/thegamebot/tree/v2/bot/cogs
(reminders.py and timezones.py happen to also demonstrate the 4th and 2nd forms of slash groups)
Neat
Is it possible to make the same command accessible with different names?
Like I want users to be able to go
/info
or
/i
Also, can I have it so that a parameter in a slash command isn't required for the command.
@bot.tree.command(name="find",description="Searches a location on a map.")
async def find(interaction: discord.Interaction, location: str,):
Like can i make the location not be neccissary to type in
discord.py uses type hints to accomplish this. Type location as an Optional[str] and assign to None as default
Alright thanks!
afaik no aliases on app commands since they are registered
I haven't personally needed to use an alias since the UX is a context menu that displays them as you type
@fast musk
same error? You'd be in the same boat as me. Google will show you the way
it isn't a python problem really
i believe the None default is implied with Optional for both slash and prefix commands so omitting it is fine
What's a good way to get my bots permissions in a guild? interaction.guild.me.resolved_permissions.manage_messages doesn't seem to work
!d discord.Interaction.app_permissions
property app_permissions```
The resolved permissions of the application or the bot, including overwrites.
Nice
or if it needs to consider the overwrites of another channel you'll probably want to use interaction.guild.me.permissions_in(channel)
wait they removed that didnt they
gah https://discordpy.readthedocs.io/en/stable/migrating.html#removals
channel.permissions_for(interaction.guild.me) then
How do I have a bot automatically add reactions to a message?
message = await interaction.response.send_message(embed=m_embed)
await interaction.message.add_reaction("1")
await interaction.message.add_reaction("2")
await interaction.message.add_reaction("3")
just like you did
Anyone an idea on how to make a AI support discord bot? Like a bot who replys to users questions and problems in a ticket like a supporter
Good question GAY STRIPER (FEMBOY), First you'll need a library of pictures of natsuki from doki doki
niezle about me
AI is a little difficult. You can always use pre-existing tools like ChatGPT, but you'll need to pay whatever fee it costs.
Yeah I mean like with ChatGPT but how do I "train" it with my information?
This isn't working, it says that interaction.message has NoneType
do you delete the message at some point?
perhaps ```py
msg = await interaction.response.send_message("Reply")
msg.add_reaction("1")
though, I'm not sure if interaction.response.send_message() actually returns anything
if not try msg = await interaction.original_response()
Slash commands do not have invocation messages, and send_message doesn’t return anything
Yeah I used this
I got it able to work and send emojis
Thank you for the help!
This is the example i found in the docs:
{"messages": [{"role": "system", "content": "Marv is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
{"messages": [{"role": "system", "content": "Marv is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
{"messages": [{"role": "system", "content": "Marv is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
but isnt this just a like keyword thing then?
I imagine it's used more like context than keyword.
Imagine "Respond in a sarcastic way, for example Question: "How far is the moon from Earth?' Response: "Around 384,400 kilometers. GIve or take a few, like that really matters.""
and if i write whats tthe distance between moon and earth? he will also answer my content?
I imagine it'll answer the question to the best of it's abilities while considering the context of the fine tuning
But it's probably better to go to a ChatGPT development related discord. as I'm not deeply familiar with ChatGPT, nor do I care.
the discord bot side of this is piping in prompt and replying with response
``py
@bot.tree.command(name="kick",description="kicks a member from the server")
async def kick(ctx, user:discord.Member, *, reason=None):
await user.kick(reason=reason)
embed = discord.Embed(title='{} has been kicked by {} for {}'.format(user,ctx.author,reason), color=0xf39c12)
await ctx.respond(embed=embed)
bot.run(TOKEN)
[output]
TypeError: parameter 'reason' is missing a type annotation in callback 'kick'
when the error says "type annotation", its referring to this: py async def kick(ctx, user: discord.Member, *, reason=None): ^^^^^^^^^^^^^^^^ you need a typehint for reason so discord.py knows what kind of parameter to use for your slash command
str is the type for strings, so reason: str would be appropriate
btw ctx.respond() doesn't exist in discord.py, and tree commands don't receive ctx Contexts
you can find examples of sending messages using interactions in their official repository
examples/app_commands/basic.py lines 41 to 44
@client.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')```
what's the difference between the @[discord.Client].hybrid_command decorator and the @commands.hybrid_command decorator?
the documentation is different but it seems like they do the same thing
none, you use the former when you have the client object, the latter when you're in a cog
that's exactly what i did lol
makes sense
the commands.hybrid_command() decorator merely creates a HybridCommand instance (which gets registered during bot.add_cog()), but Bot.hybrid_command() also adds it to the bot instance
your bot instance isn't typically available in an extension until setup() gets called though, hence why it has to be deferred to add_cog(), or at least a Bot.add_command() call in setup()
another question
how should I go about making a custom error handler in a hybrid bot?
on_command_error or bot.tree.on_error or something else?
There is no global app (slash) commands error event but you can set one for your CommandTree.
Documentation
- CommandTree.on_error
- CommandTree.error (decorator)
One way to do this is by subclassing CommandTree and overriding on_error. (recommended)
Or use the decorator:
Example
from discord import app_commands, Interaction
bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a CommandTree you define.
tree = bot.tree
# can't find your tree? -> ?tag definetree
# this will function as a global error handler for app commands
@tree.error
async def on_app_command_error(
interaction: Interaction,
error: app_commands.AppCommandError
):
...
cool, thanks
im trying to make it so where my bot always gives me permission to kick someone even when i dont have permission this is my coding
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if ctx.message.author.id == '338793925517115402':
await member.kick(reason=reason)
await ctx.send(f'User {member} has kicked.')
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"Permissions needed {error.missing_perms}")
and it wont work
anyone know why?
author.id is an int, you're comparing it against str there
!e ```py
print(123 == '123')
@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
Does anyone know how to create a bump reminder? More specifically, I don't know how to figure out when /bump is run to start a timer...
What is a bump reminder
Are you familiar with Disboard?
A bump reminder meaning after /bump is run for that bot it will start a timer to remind you later
Just detect that bot's bump message and start your timer 🤷
That's the issue though i don't know how lol
Although, I'll look through the discord.py API Reference to find something
you will probably not find anything there
bumping is a third party thing and not related to the official Discord API
I understand that, I'm looking for a way to detect the embed and the user who used the /bump
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
you would need to do some filtering to figure out of this message is a bump message but you can probably handle that
Ah ok, what about knowing the user that ran the command?
if discord.on_message uses ctx you should be able to just use ctx.author(returns username) or ctx.author.id(returns user-id) If you want to message that user await ctx.send.author()
or the equivalents for interactions (no idea what discord.on_message uses)
That works for getting the bot's id as it's the one sending the embed but for the user who ran the command it doesn't really work
You could try checking for the command instead of the bump embed? Not sure
Yeah that's the goal but i haven't found a way to check for the command because it's sent to the bump bot not my bot
Oh is the bump command a slash command?
Yep, Here is a picture of the bump command being run
Maybe there is another round-a-bout way of figuring out the user who ran the command but i haven't been able to find anything
I know it's possible as this other bot has done it but don't know how
I have no idea, never had to worry about reading from embeds, webhooks, etc that weren't integrated as part of my bot
hmm
Does a Discord accounts user ID ever change or does it remain the same since you made the account?
Always the same iirc
Thank you!
Why does it keep saying ImportError: attempted relative import with no known parent package
the line it says the error is on is just ```py
from ..ChurchEconomy import objectives
I am not able to send requests to any api using aiohttp or requests, please help
better if you ask these in #1035199133436354600
don't ping random people
read #❓|how-to-get-help please

anyone can help me?
with?
How to not ask to ask
views?
Isn't 88hrs like 3+ days?
I'm talking about the design 😁 and yes 24 x 3 = 72 hours
88 hours = 3 days | 16 hours
will maybe look into fixing that soon
Why >>> (I forgot what it's called)?
good design?
I just like >>> it gives a nice little identation
indentation*
The grey line?
Yes
Well it's not needed there but it's their choice
And green color for a moderator action idk
don't you feel it makes the embed better in this case? what would you prefer?
I'd rather say yellow looks better for that
keeping 1 uniform color for all the embeds, my bot is green themed*
I'd remove that line and keep everything rest
okay
Hmm
Well it's your choice since you are following a theme
if you see all my icons match aswell, I believe in 1 theme (except the error embeds which are red)
yeah but one day I'll make the bot public for people so u can put ur point yk?
I'm looking for people to join the team to advise me on such topics btw.. if you're interested join vision development 😁
maybe timed out user or moderator for thumbnail ig
You’re passing self when you call the argument
You need a discord.Interaction instance
is there any way to restrict the data types passed in discord.ui.TextInput?
No
Best you can do is verify the information passed in on_submit
I see
When you’re calling the argument you’re passing in self as an argument
Well I’d start with removing it
It’s your code though, and you don’t have any typehints so only you know what to pass
I want to import a @commands.group in multiple files but im getting this error: ImportError: cannot import name '' from partially initialized module '' (most likely due to a circular import) ()
in most of the files i have something like that in my imports:
from cogs.filename import one, two
from cogs.filename import three
from cogs.filename import four
What is causing the error and how can i fix it?
Send the code for your entire imported file
!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.
The whole code from every cog that i have the imports?
They are too big. If you want i can send you a small example.
Only 1
Ok ill send you tomorrow cuz its late here
@bot.command()
async def clearbans(ctx):
if ctx.author.guild_permissions.administrator:
guild = ctx.guild
bans = await guild.bans()
if len(bans) == 0:
await ctx.send('No bans were cleared.')
else:
for ban in bans:
await guild.unban(ban.user)
await ctx.send(f'{len(bans)} bans were cleared.')
else:
await ctx.send('You do not have the necessary permissions to use this command.')
bot.run(TOKEN)
``` why it dosent work
bans() isn't a list
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
oh yeah i forget to add it
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Sup fellas
schizo
what did bro do 🤔
task.start() 🫠
its not working
What is exactly not working
class MonitoringCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.compare_and_send.start()
@tasks.loop(seconds=10)
async def compare_and_send(self):
print("running")
def cog_unload(self):
self.compare_and_send.stop()
async def setup(bot):
await bot.add_cog(MonitoringCog(bot))```
Show code / error
The task isn't running
there's no error
Are you sure about the cog getting loaded?
yes
add a print() in init
Can you use cog_load and start it there?
I think start() needs to be in asynchronous func
!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.
it doesn't
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
self.index = 0
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
I found this at docs
Is it before or after migration, alot of stuff have been changed
start isnt async
It isnt
its the latest stable version
But many methods need an asynchronous function to make it usable
only async methods
I am talking about the example
non-async doesnt need to be in async but can be in async functions
yes i m talking about it too
Well if you see you can't start a ClientSession in a synchronous func
Hmm weird
async methods = should only be used inside an async function (or asyncio.create_task, asyncio.gather)
normal methods = can be used in both async and non-async
You are just not getting my point, some lib restricts a method to be only usable on an asynchronous func tho the method is synchronous

better if u try this exact example in ur bot
i did
did it work?
no
try cog_load, that example might be old
@fierce light
when i have start it in cog_load it throws this error:
Extension 'Cogs.monitoring' raised an error: RuntimeError: Task is already launched and is not completed.
maybe i should remove itt from the initiator
wrong reply
okay then it is running
wait what
yes but its not printing the thing
how are u loading ur cogs

async def loadcogs():
for file in os.listdir("./Cogs"):
if file.endswith(".py"):
try:
await bot.load_extension(f'Cogs.{file[:-3]}')
print(f'Loaded Cog {file}')
except Exception as e:
print(f'Failed to load Cog {file}')
raise e```
yeah my brain is actually rotting
y
no idea
lmao
Use logging i think
wat
!pip logging
;-;
maybe the output of print is getting stored to stdout
tried that cog in my bot
Thats why saying use logging to debug or smth xd
[2023-11-24 16:24:40] [INFO ] discord.client: logging in using static token
[2023-11-24 16:24:42] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: *).
not working
my brain going brrr
full main file? without the token
import discord
from discord.ext import commands
import logging
import os
import asyncio
from utils.config import basicconfig
bot = commands.Bot(command_prefix=basicconfig.prefix, intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"""
ready
""")
async def loadcogs():
for file in os.listdir("./Cogs"):
if file.endswith(".py"):
try:
await bot.load_extension(f'Cogs.{file[:-3]}')
print(f'Loaded Cog {file}')
except Exception as e:
print(f'Failed to load Cog {file}')
raise e
import logging
handler = logging.FileHandler(filename="Error.log", encoding="utf-8", mode="w")
asyncio.run(loadcogs())
bot.run(basicconfig.token, log_handler=handler)```
use the setup hook to load cogs
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/#making-an-advanced-bot take a look at the setup hook function here
A hands-on guide to Discord.py
from discord.ext import commands
class MyCog(commands.Bot):
def __init__(self, bot: commands.Bot):
self.bot = bot
async def setup(bot: commands.Bot):
await bot.add_cog(MyCog(bot))
what
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
wdym?
don't ping random people
sry
which code did you use?
Ur code
why tf is it not working in mine lmao
I have no idea💀
lmao its making my brain go brr
@fierce light what version of discord.py are you on?
2.3.1
how to import slash command to my bot by loading extension
i did import regular commands but the slash command did not apirs in bot app commands
i did sync the command tree
but didnt show
ok i will see
is this write
class PlayerPresenceCog(commands.Group):
def __init__(self, bot):
self.bot = bot
@commands.command(
name="player_presence",
description="Retrieves and displays player presence information",
)
async def player_presence(self, ctx, discord_id: str):
embed = await player_info_embed(discord_id)
await ctx.send(embed=embed)
no
this is a prefixed command
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
youd want ```py
app_commands.command()
jed
can you show me your main.py and full cog
in which you used my code block
@fierce light
from discord.ext import commands, tasks
class MonitoringCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.compare_and_send.start()
@tasks.loop(seconds=10)
async def compare_and_send(self):
print("running")
def cog_unload(self):
self.compare_and_send.stop()
async def setup(bot):
await bot.add_cog(MonitoringCog(bot))
import os
import json
from discord import Game, Message
from discord.ext.commands import Bot
from yoyo import read_migrations, get_backend
from config.config import get_config
from constants import intents, token
from database.moderation import ModerationDB
class Molina(Bot):
def __init__(self, *args, **kwargs) -> None:
super().__init__(
*args,
command_prefix="?",
intents=intents,
**kwargs
)
self.filters = [] # global list of filtered words
async def get_prefix(self, message: Message) -> str:
pfx = get_config("bot", "commandPrefix")
return pfx or "?"
async def update_filters(self):
db = ModerationDB()
filters = await db.get_filtered_words()
self.filters = [f[1] for f in filters]
async def on_ready(self) -> None:
await self.wait_until_ready()
await self.update_filters()
await self.change_presence(activity=Game(name="Mobile Legends: Bang Bang"))
print(f"{self.user} is ready.")
async def setup_hook(self) -> None:
config_path = "bot/config/config.json"
if not os.path.exists(config_path):
with open(config_path, "w") as c:
json.dump({}, c)
for cogs in os.listdir("bot/cogs"):
if cogs.endswith(".py"):
await self.load_extension(f"cogs.{cogs[:-3]}")
url = f"sqlite:///./bot/database/mlbbph.db"
backend = get_backend(url)
migrations = read_migrations('./migrations')
backend.apply_migrations(backend.to_apply(migrations))
molina = Molina()
molina.run(token)
@sharp whale
why would any one name the bot instance as molina lmao
u shouldnt really do stuff in on_ready
its triggered multiple times throughout a bots lifespan
yeah this is an old bot
fair
ugly ahh code 🔥
LMAO 💀
Asher
halp me pls
should i try my code in replit or something
@fierce light bro i just called the start function in "on_ready" listener and now it works lmaoaoaoooaoao
lmfao
do it in "setup_hook"
is this write
from discord import app_commands
from discord_py import player_info_embed
class PlayerPresenceCog(app_commands.commands):
@app_commands.command(
name="player_presence2",
description="Retrieves and displays player presence information",
)
@app_commands.describe(discord_id='the member to retrieve information for')
async def player_presence(self, ctx, discord_id: str):
embed = await player_info_embed(discord_id)
await ctx.response.send_message(embed=embed)
async def setup(bot):
bot.tree.add_command(PlayerPresenceCog())
!paste your code here
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.
cog and bot
it works now
aight cool what was the issue the cog loading i am gonna assume
nope
https://fallendeity.github.io/discord.py-masterclass/slash-commands/#creating-a-slash-command go through this it teaches you on how to work with slash commands in a pretty detailed manner
A hands-on guide to Discord.py
for the cog u need to inherit from commands.Cog and in setup await bot.add_cog(PlayerPresenceCog(bot)) also u can rename ctx to interaction for more clarity
thx
from discord import app_commands
from discord.ext.commands import Cog
from discord_py import player_info_embed
class PlayerPresenceCog(Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(
name="player_presence2",
description="Retrieves and displays player presence information",
)
@app_commands.describe(discord_id='the member to retrieve information for')
async def player_presence(self, ctx, discord_id: str):
embed = await player_info_embed(discord_id)
await ctx.response.send_message(embed=embed)
async def setup(bot):
await bot.add_cog(PlayerPresenceCog(bot))
wrote that on top of my head
dunno if its right
u cant import ext like that
How can I wait for a user to move to a voice channel?
thx for that
np
on_voice_state_update() event probably
hhmm
How can I send a message in the voice channel after the user has been moved?
create_vc_channel_id = 1151598666239463488
# Check if the member joined the "Create VC" channel
if before.channel is None and after.channel and after.channel.id == create_vc_channel_id:
# Wait for the user to be moved to another voice channel
def check(new_after):
return new_after.channel and new_after.channel.id != create_vc_channel_id and new_after.channel != after.channel and new_after.channel.guild == after.channel.guild
try:
new_after = await client.wait_for('voice_state_update', check=check, timeout=10.0)
except asyncio.TimeoutError:
print(f'Timed out waiting for {member.display_name} to be moved to another channel.')
return
await new_after.channel.send(
f"{member.mention} You can block a member from joining your voice channel. When you block someone, they won't be able to see your voice channel. Visit [#1151576650069311499](/guild/267624335836053506/channel/1151576650069311499/) to manage your voice channel.")
return
Voice channel?
!d discord.VoiceChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
Well yeah just use it?
And depends on in which channel do you want to send msg like before or after
After
[2023-11-24 14:48:12] [ERROR ] discord.client: Ignoring exception in on_voice_state_update Traceback (most recent call last): File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 441, in _run_event await coro(*args, **kwargs) File "D:\discord bots\blitzcrank.py", line 2313, in on_voice_state_update new_after = await client.wait_for('voice_state_update', check=check, timeout=10.0) File "C:\Users\Gamer\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 445, in wait_for return fut.result() File "C:\Users\Gamer\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py", line 474, in dispatch result = condition(*args) TypeError: on_voice_state_update.<locals>.check() takes 1 positional argument but 3 were given
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState).
The following, but not limited to, examples illustrate when this event is called...
@young dagger check needs 3 arguments
Do I need to fetch the voice channel before sending a message?
Checking: Beerhunter, ➕ Create VC, Aram Timed out waiting for Beerhunter to be moved to another channel.
Aram = New voice channel in this case
u need to have the voice channel object to send the message
its method under the voice channel object
For some reason when two users are joining create_vc_channel_id at the same time. The bot sends 2 (double) messages to the same user and ignoring the other one
Anyone have suggestions gor my bot?
I mean i successfully made a bot
But i hope the dialogue change according the guild(server)
Is there there way?
I already made 2 main.py , fuctions are same but i edited dialogue
Hey guys! Is there a complete guide for making discord bots from scratch?
I really just started making one
in replit
And i don't want tto discontinue
but am getting stuck a lot
here is somewhat of a guide but its relatively complete
since i am a complete beginner
Are you sure? thanks!
its guides u to make a bot from scratch right from installing python and creating the bot
oooh ok
few areas are still yet to be documented but the slash command and basic commands stuff is present
i did on replit is that fine asw?
i suggest developing locally
Adding text in embeds?
yeah
so like installing python?
only views is left iirc
yeah that guide guides through that too
oooh
A hands-on guide to Discord.py
omg thanks a lot!!
start from here lmk if u get stuck somewhere
Thnx!!!!!! Can I dm you too if I get stuck?
ping me here I'll answer if i am active if not there will probably be other people active here helping as well if it's some doubt with the guide u can dm me or leave a comment
Ohhh ok thanks!!!!

Here it's said making a folder
Dows that mean on the pc?
@shrewd apex
?
yeah
Ooh. Ok
So then I just make a folder on pc
then whats a code editor
just python right?
@shrewd apex ?
Sorry for the pings!!

Python?
Ping me instead
python is the language
oooh ok
And yeah you need a code editor to like write python codes, but you can use notepad too 💀
similar to how u write English but using ms word
vscode pycharm etc is the ms word equivalent for coding it autocompletes and corrects your code
yeah



did u add python to path u had to mark a check box when installing
type in python --version in the terminal
have u installed python?
i have
Yes!!
u downloaded the installer right from python website?
can u double click on that
and send me a screenshot of the window that opens
also on another note i dont think discord bots run on python 3.12 yet coz aiohttp max is 3.11
Yes!!
which one?
the installer
so should i install 3.11 instead?
yeah
install the 3.11 installer and send me a screenshot pf the window that pops up
Alright i will!
the first one but for 3.11
yeah
Ok
asher, i got another problem :)
the error handler isn't getting triggered```py
@commands.command(name="setnotificationchannel")
@commands.has_permissions(administrator=True)
async def setnotificationchannel(self, ctx: commands.Context, channel: discord.TextChannel):
LogChannelSet(value=channel.id)
await ctx.send(f"Successfully changed the channel for Notification updates! to {channel.mention}")
embed = discord.Embed(title="Channel Set!", description="This channel has been set for VPS updates notification", color=discord.Color.green())
await channel.send(embed=embed)
@setnotificationchannel.error
async def setnoti_error(self, error, ctx: commands.Context):
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You don't have the required permissions to use this command, you need __administrator permissions__ in order to use this command!**")
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("**Please mention a channel**\n `!setnnotificationchannel #channel`")```
there's no error in the logs
add an else statement and put in await ctx.send("Uknown error")
also i think the order is wrong
not working
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
Ohke
did that earlier asw
done
ok
