#discord-bots
1 messages · Page 283 of 1
i know that felling
Don't ignore 😭
I'm working on it I promise.
But when
?
yeah why not
No clue I got some nice idea's that I'd like to work out.
just copy it wrap over a command and accept inputs from command
@command()
async def ...(..., text: str, mode: Literal["encrypt", "decrypt"], ...):
if mode == "encrypt":
send(encrypt(text))
...
just brief showcase
if you wanna find out what Literal is check out this :j https://fallendeity.github.io/discord.py-masterclass/converters/#literal
A hands-on guide to Discord.py
thank you!
sorry to bother you again. I copied this, made couple of small changes. But where can I put the script in order for this to actually work?
the bot intents are on the emojis are uploaded into my server why isnt the bot sending the nitro emoji
like you do for every other command
Titles can't have custom emojis iirc
oh
I guess I am supposed to know by now...
how did you do for commands before?
i placed it in field but its still not working
Can you help me a bit more? So sorry, but I dont know what to do
They need to be in the form <:name:id>, not like you would on Discord
basically i just added @command() decorator and for you it will be @client.command()
then you need to adjust the name and params you want
and actual body
and where do I add the body?
function body i mean
guys rate this i made new dashboard the things like names are examples
Yes I know
where else can you place function body
Like I have actually no idea where
def f():
# body
I havent ever done this before
yeah its like that
bro indents
wait a damn minute is this first server yours?
nop
example
Field values, not names
wow good job Sherlock i literialy got polish words on profile and u just saw it
yeah cause i read everyones about me
Description and field values are the only sections where you can add custom emoji

so how u guys rate it?
solid 7/10
thx
its fully customizable tho
Down like that?
u add name and it shows
no you need to actually send the result
send was just placeholder for me
uhhhhhh
and now you need to define encrypt and decrypt functions
if mode == "encrypt":
send(encrypt(text))
if mode == "decrypt":
send(decrypt(text))
``` since you try to call them
and I do that how exactly? Trust me I would go to youtube but it was no help
This is like teaching your dad how to play CoD
well i see you have trouble with functions so you need to learn syntax and why we need those before continuing
so, basically this is WAY too advanced for me?
i wouldnt say its advanced you are just missing some concepts
ok
i broke it a litle bit
i hopped on replit and tested it witg my main
and it spammed servers that am on
Nah its fine
zoom in
this is how it is
and this is how it sends
Are you sure your bot has access to that emoji? Are emoji intents enabled?
If you copy this Emoji string and paste yourself does it send the Emoji?
yep
i coped the whole thing and it sent like this
So either the Emoji string is wrong or you and bot does not have Access to the emoji
it sends normally through the emoji menu and the emoji is also uploaded to the server and the bot has the intents on aswell
What does "does not work" mean
that it isn't working 😌

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start) coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect) + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login).
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
Read the warning
hanlo
whats up guys how do i keep a single database connection in multiple cog files
like, currently i am having to create a separate connection for each cogs
:)
create a db attribute for the bot
Could you show an example brother?
what db are u using?
MySQL
bot.db = use_db_pool and u can access using self.bot.db in cogs
also mysql is sync u might wanna use asyncpg or motor (mongodb)
!pip aiomysql
Hi, does discord support the use of Select menus in Modals?
No
They accidently released them so long ago but they still haven’t added them back yet
where do you get the discord colour codes
wdym?
google ig
yes
how to track when user coming in online?
does discord stores the name of the moderator/admin who bans a user?
Yes, in the audit log
Audit log
is there a way to fetch it?
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
ooo thanks
Np
Hello, is it possible to limit the choice of discord.Member from the slash command argument?
a message doesn't have a color
you might want to edit the message embed's color
you could do
message: Message = ...
embed: Embed = message.embeds[0]
embed.colour = 0xFFFFFF
await message.edit(embed = embed)
never tried it before, idk if it will work
!d discord.Embed
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...
Just set the color argument in the instance creation 
Limit the choice?
he's editing it
What
wdym what
What do you mean by he's editing it
I don't know about you, but it seems to me that they're creating a new instance
For example, I would like one of my command argument to be a user parameter. But discord automatically displays the whole list of users in the server. Any way I can place a restriction on the list of users to be displayed?
@slate swan you passed the color parameter outside the embed creation
Well, I see no other way than to supply the choices yourself
Like with autocomplete
Trying to create a coroutine to pull a line from a txt document and place it inside an embed then call that coroutine inside a slash command and just send message containing an embed. I keep getting an error that 'embed' is not defined, but it's defined inside the coroutine so is there a way to do that?
just send the code
embed is defined in a different function, you need to define it in the same scope (i.e. function) as you use it, or a scope above that (above as in, encapsulates it)
Got it
embed = await fact()
Or use the embed that the coroutine return 
Thanks
np
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
edit the view with the button.disabled to True in the button object
ahh autocomplete only works for str, int or float types, unfortunately
I'd just return the members' names
Why doesn't this work inside a tasks.loop()?
The print gives me None
Can we get a user by their id using discord.User(id)?
Like:
user = discord.User(id=1231231421231231)
print(user)```
!d discord.Client.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.Client.fetch_user or this
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user) instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
:o ty
Did you edit the function? A function will return None if you didn't return anything using the return statement
Hello, could someone enlighten me on guild vs global commands - how do i prevent my guild commands from syncing globally? My bot is showing duplicates of my slash commands...
How would that even work
via python attributes
yes ofc
Can u show how are u syncing them?
can someone explaine how i can make every command from my discord bot in a excluded file
do i need classes?
I advise using cogs
But not entirely one command per cog i would group them info categories and mąke one cog per category
!d discord.ext.commands.Bot.add_command
If you want to have only the commands in the files, you need to do it manually
But cogs are usually enough
add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command) or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group) shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError) instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException)
Changed in version 2.0: `command` parameter is now positional-only.
I got a bit confused when doing this as quite like 1 command per file so grouped them in the file structure instead
Hello!
I was wondering if someone could help me fix this keyerror!
This is part of the code
response = get('https://economy.roblox.com/v2/groups/{Stuff.groupid}/transactions?cursor=&limit=10&transactionType=Sale', cookies={'.ROBLOSECURITY': Stuff.cookie})
for purchase in response.json()["data"]:
Stuff.pastids.append(purchase['idHash'])
and the keyerror is "data"
Idk what is wrong
and no clue on how to fix thta
prolly print the response?
and see the output
the select menu pops up but when i select something, nothing happens. no errors in my terminal and nothing prints
two main languages to write discord bots are javascript and python
dont know which one has more bots
send your question and we can help
Ok wheres the cog system in discord.py so i can examine it and grab functions
i was following someone elses solution to add options to a select menu based on stored data but they didnt include how to setup the callback so im confused as to why mine isnt working. heres the one i was following:#1054851673236971601 message
class MyView(discord.ui.View):
def __init__(self, ctx, user_id):
super().__init__(timeout=None)
self.ctx = ctx
self.user_id = user_id
self.durum = None
async def interaction_check(self, interaction):
return interaction.user.id == self.user_id
@discord.ui.button(label="Yazı", style=discord.ButtonStyle.primary, custom_id="yazi")
async def yazı_button_callback(self, button, interaction):
print(interaction)
channel = self.ctx.channel
self.durum = 2
self.stop()
user_id = self.user_id
await self.ctx.invoke(self.ctx.bot.get_command('b'))
its working but
i got this err
this interaction failed
I coded it so that a new embed is sent when the button is pressed.
interaction fails because youre not responding to the interaction
how can i
await interaction.response.send_message()
where exactly should i place it
i did like this
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response).
New in version 2.0.
give that a read
g1 = int(g1)
g2 = int(g2)
guild1 = client.get_guild(g1)
guild2 = client.get_guild(g2)
await ctx.send(f'{g1} + {g2}')
await ctx.send(f'{guild1} + {guild2}')
for channel in guild2.channels:
await channel.delete()
await asyncio.sleep(5)
for channel in guild1.channels:
await guild2.create_channel(channel)
Anyone know why this says it cant create the channel?
Guild has not attribute 'create_channel'
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
check the create channel methods
?
?
wym
check the docs for the create channel methods
create_channel doesn't exist
create.text_channel
nobody has any ideas on this then?
still wouldnt work lol
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel) for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
Could somebody send the documentation for channel.send()? I cannot find it for the life of me
what wasnt mentioned there is that the select menu they created didnt actually have any callback registered
!d discord.TextChannel.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**.
thanks
np
yea thats my struggle right now, i tried rewriting it to the same way its written in rapptz github but i keep getting an _underlying error
what did you write, and what was the traceback?
the two official ways to define the callback are:
- subclassing Select
class MySelect(discord.ui.Select):
async def callback(self, interaction):
...
my_view = discord.ui.View() # can also be a subclass
my_view.add_item(MySelect())``` 2. using the select() decorator in your View subclass
```py
class MyView(discord.ui.View):
@discord.ui.select(options=[], ...)
async def my_select(self, interaction, select):
...```
this is what i tried after that didnt work
if you're overwriting __init__, you have to invoke super().__init__() to initialize the parent class
i.e. the same thing you did in your rulesview, just for your dropdown class
so after i add the options i need to follow it up with super().__init__(self)...?
or do i add_item(self) lol
not exactly sure how to utilize that properly
i got it, thanks a ton 
can someone help me with my unban command because its saying this application did not respond
heres my code
@bot.tree.command(name="unban")
@app_commands.describe(user_id="Provide the user's ID to unban.")
async def unban(interaction: discord.Interaction, user_id: str):
if interaction.guild.me.guild_permissions.ban_members:
try:
banned_users = await interaction.guild.bans()
user_ids = [entry.user.id for entry in banned_users]
try:
user_id_int = int(user_id)
except ValueError:
await interaction.response.send_message("Invalid user ID provided.")
return
if user_id_int in user_ids:
user_to_unban = discord.Object(id=user_id_int)
await interaction.guild.unban(user_to_unban)
await interaction.response.send_message(f"User with ID {user_id_int} has been unbanned.")
else:
await interaction.response.send_message(f"User with ID {user_id_int} is not banned.")
except discord.Forbidden:
await interaction.response.send_message("I don't have permission to unban members.")
else:
await interaction.response.send_message("I don't have permission to unban members.")
Remove the error handler and show the error
okay
2023-08-09 20:48:46 ERROR discord.app_commands.tree Ignoring exception in command 'unban'
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/home/container/VP.py", line 125, in unban
user_ids = [entry.user.id for entry in banned_users]
TypeError: object async_generator can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/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/container/.local/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 'unban' raised an exception: TypeError: object async_generator can't be used in 'await' expression
@final iron
!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...
its async for
where do i put it
ohhh async for unban(interaction: discord.Interaction, user_id: str)
??
Why are you getting the guild bans anywaym
tbh idk
i didnt know whatelse to do
no.
when you iterate over bans you need to use async for instead of normal for loop
sorry i suck at this
all you need to do is guild.ban(discord.Object(id = id_to_ban))
You can't modify other people's about me
Why would it be??
What do you even mean by bio
About me?
That's not a thing
Just do it normally
And what's stopping bots from setting a user's about me to slurs?
You did not think this through
Not really. These aren't server specific, even if they were users wouldn't want them changed
Is there any way I can remove interaction without it throwing an error?
async def country_autocomplete(
self,
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
I just don't like how it's unused tbh
Unused parameters are named with underscores
Your linter will probably stop screaming at you
Absolutely no warnings will be acceptable
It's also saying a refrence cannot be found, can anything be done about that?
There's also no autocompletion for it which I don't like
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
Hmm it's not Optional[InteractionResponse] either
it's a pycharm issue
I figured
Sometimes it doesn't show suggestions, can anything be done about it on my end?
you can disable inspections for that type of warning in your pycharm settings or comment it out with # noinspection PyUnresolvedReferences
I'd rather keep it in for those situations where I actually did make a mistake
Good to know though
Guess I'll be stuck with warnings
Are there any advantages to implementing cogs when your bot is exclusively slash commands?
Before I just used it to help simplify creating the help command so it would group them automatically
Makes your code look clean and easier to manage
Guys, I found a way to make a discord yt music bot thats legal

I am stealing that emoji

its called pytube btw
WHY IS IT SO CUTE
pytube is still against YouTube's terms of service
!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)
This extends to pytube
ugh, tis why I didnt read them
it still works though (kinda)
Now my dumbass just has to figure out how to play the mp3 file
Wish me luck
That's not really possible
Using any automated way to access the material is prohibited
Not really
They just don't profit when people use these bots as they bypass the ads
It also stresses the system out more so they avoid it
Most of these music streaming services have the same TOS
wassup guys
i need help with a thing
File "c:\Users\User\Documents\GitHub\RP-Utilities\bot.py", line 37, in prefix_setup
prefix = await self.db_loop.run_until_complete(self.database.get_prefix(guild_id=ctx.guild.id))
^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'guild'. Did you mean: 'guilds'?
why am i getting this error?
ctx is not a commands.Context object
what are you trying to do
custom prefix as I can tell, share more of your code pls
anyone looking for a bot dev?
no
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.
@severe sonnet
sure
take a look:
https://github.com/HirukaRogue/RP-Utilities
i see, thought my problem is with guild thing
where it seems to have problems
Just send where/how you're calling the function
!code
okay
class Bot(commands.Bot):
def __init__(self) -> None:
super().__init__(
intents=INTENTS,
command_prefix = DEFAULT_PREFIX,
case_insensitive=True
)
self.database = Database()
print("Bot Connected!")
async def setup_hook(self) -> None:
await self.database.connect("mongodb://localhost:27017")
self.db_loop = self.database.dev_client.get_io_loop()
self.command_prefix = await self.prefix_setup(self)
for extension in EXTENSIONS:
await self.load_extension(extension)
await self.add_cog(PrefixCog(self))
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
async def prefix_setup(self, ctx: commands.Context):
prefix = await self.db_loop.run_until_complete(self.database.get_prefix(guild_id=ctx.guild.id))
if prefix:
return prefix
else:
return DEFAULT_PREFIX
i'm calling it from setup hook
in my Bot.py
like, main function
read it please
"This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix."
well, it has a string to be called, and also i'm calling it from my DB, but i can't give it the guild id to search
cus this error freaks me
mate
like, i'm trying to parse the guild id to my function get_prefix
read
the
docs
async def get_prefix(self, *, guild_id: int) -> str | None:
document = await self.db.prefixes.search_one({'guild_id': guild_id})
if document is not None:
return document["prefix"]
else:
return None
callable that takes in the bot as its first parameter and discord.Message as its second parameter
i do it
but why it errors?
like, it seems all correct
the main problem is parsing guild_id to get the id of the guiild
Look at it, carefully
well, i'm missing on it
i'm not getting where you guys want me to reach on
Missing on what
like, i get that the prefix need to be a string and shit, but the problem i'm having is passing the guild_id to my database to it get the prefix it has contained
This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix.
there's no point of you don't read
What are we on about again?
this
but i read, you guys that aren't getting what i need
we get what you need
Hey!
like, how do i get the guild id]
anybody can help me?
we are giving what you need, you just need to read
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.
Nobody can ever help you if you don't ask any question(s)
"This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix."
Traceback (most recent call last):
File "main.py", line 7, in <module>
discord.opus.load_opus("./asd.0")
File "/home/runner/Youtube-bot/venv/lib/python3.10/site-packages/discord/opus.py", line 264, in load_opus
_lib = libopus_loader(name)
File "/home/runner/Youtube-bot/venv/lib/python3.10/site-packages/discord/opus.py", line 187, in libopus_loader
lib = ctypes.cdll.LoadLibrary(name)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/ctypes/init.py", line 452, in LoadLibrary
return self._dlltype(name)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/ctypes/init.py", line 374, in init
self._handle = _dlopen(self._name, mode)
OSError: ./asd.0: ELF file's phentsize not the expected size
i have this error
i have searched in every place, every forum but i dont seem to find a solution
okay so, second parameter...
a Message objects holds a guild object from which you can get the guild id, so as long as you make the function signature correct it'll be easy
!d discord.Message.guild
The guild that the message belongs to, if applicable.
!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.
https://paste.pythondiscord.com/WOWQ I have this code here for an anti bad word system. I have a function called ReplacedoubleCharacters and it detects double characters like hiiiiiii. But it’s deleting “1” and I feel like it’s that function.
do someone know a free vps instead of oracle and aws to host my bots ?
Where can I read about possible ways of implementing graphical interactions? To be precise, I want to know is it possible to implement some kind of turn based games and what may be used as interactive GUI
Discord only got buttons, dropdowns and modals
Just use fuzzy matching.
Implementation examples can be found in discord.py repo
That's enough for input. But can it generate images and show em to specific user only with those inputs?
It's not UI issue is it
well, some elements are good to be drawn, and I asked about GUI at first, even if user cannot interact with that image, at least they may see info
What’s that?
I just wanna know why it is deleting 1
Record linkage (also known as data matching, data linkage, entity resolution, and many other terms) is the task of finding records in a data set that refer to the same entity across different data sources (e.g., data files, books, websites, and databases). Record linkage is necessary when joining different data sets based on entities that may o...
Ok
But I don’t wanna use it
I just wanna know why it is deleting 1
And fix it
!e ```py
def replaceDoubleCharacters(string):
lastLetter, replacedString = "", ""
for letter in string:
if letter != lastLetter:
replacedString += letter
lastLetter = letter
return replacedString
print(replaceDoubleCharacters("1"))
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
@formal basin ?
pep 8 !
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | if None + sex == None:
004 | ~~~~~^~~~~
005 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
!e ```py
def replaceDoubleCharacters(string):
lastLetter, replacedString = "", ""
for letter in string:
if letter != lastLetter:
replacedString += letter
lastLetter = letter
return replacedString
print(replaceDoubleCharacters("1"))
@formal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
*1*
@cloud dawn
You forgot the **
!e ```py
def replaceDoubleCharacters(string):
lastLetter, replacedString = "", ""
for letter in string:
if letter != lastLetter:
replacedString += letter
lastLetter = letter
return replacedString
print(replaceDoubleCharacters("2"))
@formal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
*2*
But it doesn’t censor 2
Here
!e ```py
def replaceDoubleCharacters(string):
lastLetter, replacedString = "", ""
for letter in string:
if letter != lastLetter:
replacedString += letter
lastLetter = letter
return replacedString
print(replaceDoubleCharacters("hiiiiiiii"))
@formal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
hi
I've no clue what you want it to do.
Well, that's how the function was written 🤷
And it does exactly what it was written to do
Did you check the link?
Yes?
Did you see the other file
Yes??
print("test56")
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"logs:{str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"3bad word detected2 logs: {message.guild.id}") ```
This is the problem
What is "the problem"?
What does string_without_spaces contain?
@client.listen()
async def on_message(message):
if message.author.id == client.user.id:
return
message_content = message.content.lower()
string_without_spaces = message_content.replace(" ", "").replace("î", "i").replace("ï", "i").replace("í", "i").replace("ī", "i").replace("į", "i").replace("ì", "i").replace("ŵ", "w").replace("è", "e").replace("é", "e").replace("ê", "e").replace("ë", "e").replace("ē", "e").replace("ė", "e").replace("ę", "e").replace("ŷ", "y").replace("û", "u").replace("ü", "u").replace("ù", "u").replace("ú", "u").replace("ū", "u").replace("ô", "o").replace("ö", "o").replace("ò", "o").replace("ó", "o").replace("œ", "oe").replace("ø", "o").replace("ō", "o").replace("õ", "o").replace("à", "a").replace("á", "a").replace("â", "a").replace("ä", "a").replace("æ", "ae").replace("ã", "a").replace("å", "a").replace("ā", "a").replace("ß", "ss").replace("ś", "s").replace("š", "s").replace("ł", "l").replace("ž", "z").replace("ź", "z").replace("ż", "z").replace("ç", "c").replace("ć", "c").replace("č", "c").replace("ñ", "n").replace("ń", "n") ```
That’s what it is. I think it’s Because of the replace.
But I can’t see 1 in there
@formal basin what are you even trying to do
Holy
Anti bad word system
for loops left the chat.
Like i said just use fuzzy matching.
Cleans all of this up.
For word in bad_words:
If word in words_to_check:
Replace
sorry, was not at pc, thank you!
feet -> fet
I'm trying to make a music bot but PyNaCl gets on the way when i try to install it it says Failed to build PyNaCl does any of y'all have solutions? (I'm using Termux if you're wondering)
We don't help with music bots, sorry.
Yeah I cant see a 1 in here
async def on_message(message):
if message.author.id == client.user.id:
return
key = f'antibadwords:{message.guild.id}'
if r.exists(key):
if profanity.contains_profanity(message.content) or profanity.contains_profanity(replaceDoubleCharacters(message.content)):
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"logs:{str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"1bad word detected logs: {message.guild.id} {message.content}")
``` it was this code
What message gets sent that is catched?
1
it think 1 is in the bad word list
im gonna allowlist it
and see if it works
I allow listed it and it still detected it
Hi im new to sqlite, when i build the connection should I connect it once when i start the bot or connect and close on command use?
You should connect once
hi
role1 and role2 aren't giving the roles after a member reacts to it
but role3 and tos4 does give them the roles after the member reacts to it
all ids are correct
someone pls help me fix this code
pls someone help
@sick birch
@fierce crag
please don't ping random people
i'm trying to ping helpers
helpers are not obliged to help
role1 and role2 have different code
to role3 and role4
can you help me change the code?
cause role3 and role4 have only 1 reaction emoji
and role1 role2 doesnt
...
?
@bot.command()
@commands.has_permissions(ban_members=True)
async def role1(ctx):
embed = discord.Embed(
title=":C_Flames: **age**",
description=":greenstar: / **13**\n:redstar: / **14-15**\n:purplestar: / **16-17**\n:yellowstar: / **18**",
color=0x00ff88
)
embed.set_footer(text="~ react")
message = await ctx.send(embed=embed)
emojis = [
":greenstar:",
":redstar:",
":purplestar:",
":yellowstar:"
]
for emoji in emojis:
await message.add_reaction(emoji)
bot.reaction_roles_message1 = message # Store the message object
@bot.command()
@commands.has_permissions(ban_members=True)
async def role2(ctx):
embed = discord.Embed(
title=":C_Flames: **gender**",
description=":male: / **male**\n:female: / **female**",
color=0x00ff88
)
embed.set_footer(text="~ react")
message = await ctx.send(embed=embed)
emojis = [
":male:",
":female:"
]
for emoji in emojis:
await message.add_reaction(emoji)
bot.reaction_roles_message2 = message # Store the message object
@bot.command()
@commands.has_permissions(ban_members=True)
async def role3(ctx):
embed = discord.Embed(
title=":nsfw: **nsfw**",
description="react to access **nsfw** channel",
color=0x00ff88
)
message = await ctx.send(embed=embed)
await message.add_reaction(":nsfw:")
bot.reaction_roles_message3 = message # Store the message object
@bot.command()
async def tos4(ctx):
embed = discord.Embed(
description="- :verify2:\n**Click the emoji to access other channels**",
color=0x00ff88
)
embed.set_footer(text="~ react")
message = await ctx.send(embed=embed)
await message.add_reaction(':verify2:')```
how can i solve those errors?
windows 11, VScode19', python3.7.9
see the difference? @fresh smelt
What library did you install
do you have multiple python versions installed?
now reactions doesn't even pop up
yes. so it might be an issue right?
yes, are you on windows?
btw discord.py doesn't support python 3.7.9
Yes you need to change interpreter Path to version you installed the package on
the least python version supported is 3.8
yes but your issue isn't directly related to that
you can use the following command if you're on windows
py -3.8 -m pip install -U discord.py
-3.8 can be replaced with the python version that you have installed
(╯°□°)╯︵ ┻━┻
ok. command prompt printed few things. already restarted and changed the interpreter. but there are still same problems. anything else?
so same warnings ?
!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
what python version are you using now
3.10.4
https://paste.pythondiscord.com/VOBA
its switching codes now. its this code now not the other one. This code detects people using emojis to bypass the filter
so you replaced the 3.8 with that version correct?
!dashm use this to install your library
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
yes
guys, what discord.py documentation is better for me that always miss something?
like, a doc that i can use it with more easiness?
And set interpreter in vscode to point to this version you are using
but i have this already
and don't get lost?
that's weird then should work
Ctrl shift p and then type interpreter

same thing
I mean what you selected
And what was in the list
(that's why I always use virtual environments)
3.10.4 interpreter. @glad cradle asked for bottom so firstly i'll send this and after those interpreters
Its the same thing i belive
3.10 indeed
yeah
How about you do python --version
And this?
3.10.4 as said before
What package you trying to install?
Discodpy?
guys i'm completly beginner so pls help
yes
I mean it should work
yes. it should but doesn't
try python -m pip install -U discord.py this time
Do python -m pip show discord.py
all of suden there is no module named pip 💀 a few minutes ago there was but now not
downloaded pygame i discord.py and now there's no such module
pip install pip

😨
💀
Many python versions is making him lost
ggs how to fix this now
yeah thanks guys 💀
maybe a virtual environment would help but heh
i get this error after a while when running bot:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "bank.py", line 140, in balance
mycursor = db.cursor()
File "/home/container/.local/lib/python3.8/site-packages/mysql/connector/connection.py", line 809, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: MySQL Connection not available.```
Like, for half an hour or so the database connection is normal but then it shuts down
And how do you connect to it
mysql.connector
isn't mysql a blocking library?
Also for discord bot i would suggest using async lib
!pypi aiosql
hmmm
!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!
Dam they only provided library for postrges and mongo
not sure why the connection is not available though
yeah i dont either
if mysql uses .sql file aiosql is ok
ye mysql uses .sql file
then use this
i think both have very different structure
might need to rework most of the code
ok thanks bros lemme give it a shot
nah
Well you will need to await most of the database calls
hmm
Is it possible, in the same way you can do it on your own profile, to set a status emoji for a bot?
!d discord.Activity.emoji
The emoji that belongs to this activity.
i belive this should be it
Perfect thank you
anyone willing to help me with my music module?
it downloads files as .webm succesfully and isnt giving me any errors but for some reason still wont play in the vc.
https://paste.pythondiscord.com/BUEA
Theres the code
Help would be greatly appreciated as I have been trying to figure it out for hours
!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)
Any pro tips on how to get a command that can run my script? I have tried to learn basics of python
im trying to make a code where u import roblox cookies in cookies.txt and it makes a game on roblox with a template like template.rbxl and it makes it and publishes it to roblox and it shares it in a server in discord
i need help
so can anyone help me
I dont need help with ytdl I need help with discord.py
and potentially ffmpeg
we cant help you with a project that uses libraries that break youtube tos
smh
just use jishaku
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
well, if someone actually wants to help, dm me
someone help me please
This does not sound like something roblox would allow
with¿
is it possible to make a discord bot to give me roles in a discord server thorugh terminal
and if so is it gonna be hard
In your server it’s possible but not hard afaik, in another server kinda hard
What would be the difference
aslong as the bot has perms
‘d say so 🤔
terminal command only?
cause its easy to do just via discord bot command
but not entirely sure how to approach it with a terminal command
obv
that can be as complex as you want it to be, but the simplest option would be making an HTTP request with the guild+user+role ID that you're adding, plus your bot token for authentication
endpoint: https://discord.com/developers/docs/resources/guild#add-guild-member-role
see also their reference docs for using the API: https://discord.com/developers/docs/reference
You can check this out
I think this bot can retrieve info of a server not sure about this but you can send messages to a server via terminal
im trying to make a code where u import roblox cookies in cookies.txt and it makes a game on roblox with a template like template.rbxl and it makes it and publishes it to roblox and it shares it in a server in discord
can someone help me
im trying to make a code where u import roblox cookies in cookies.txt and it makes a game on roblox with a template like template.rbxl and it makes it and publishes it to roblox and it shares it in a server in discord
they allow it
please help though
was wondering if anyone knows how a code for discord bots for twitch and if they could assist me.
ask your question
im trying to make it where when any user listed in the code goes live on twitch, it sends a message in a guild
is anyone gonna helo me
like what streamcord does
.
That's what this channel is for 
0|main | Ignoring exception in on_message
0|main | Traceback (most recent call last):
0|main | File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|main | await coro(*args, **kwargs)
0|main | File "/home/Runa/bot/cogs/leveling.py", line 82, in on_message
0|main | await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?', (xp, author.id, guild.id))
0|main | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/cursor.py", line 37, in execute
0|main | await self._execute(self._cursor.execute, sql, parameters)
0|main | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/cursor.py", line 31, in _execute
0|main | return await self._conn._execute(fn, *args, **kwargs)
0|main | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 129, in _execute
0|main | return await future
0|main | File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 102, in run
0|main | result = function()
0|main | sqlite3.OperationalError: database is locked
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot or message.guild is None:
return
author = message.author
guild = message.guild
async with self.bot.db1.cursor() as cursor:
await cursor.execute('SELECT levelsys FROM levelSettings WHERE guild = ?', (guild.id,))
levelsys = await cursor.fetchone()
if levelsys and not levelsys[0]:
return
await cursor.execute('SELECT xp FROM levels WHERE user = ? AND guild = ?', (author.id, guild.id))
xp = await cursor.fetchone()
await cursor.execute('SELECT level FROM levels WHERE user = ? AND guild = ?', (author.id, guild.id))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute('INSERT INTO levels (level, xp, user, guild) VALUES (?,?,?,?)', (0, 0, author.id, guild.id))
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
if level < 5:
xp += random.randint(1, 3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?', (xp, author.id, guild.id))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp += random.randint(1, 3)
await cursor.execute('UPDATE levels SET xp = ? WHERE user = ? AND guild = ?', (xp, author.id, guild.id))
if xp >= 100:
level += 1
await cursor.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id))
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id))
async with self.bot.db1.cursor() as cursor:
await cursor.execute('SELECT levelChannel FROM levelchannel WHERE guild = ?', (guild.id,))
channelID = await cursor.fetchone()
if not channelID:
return
channelID = channelID[0]
channel = guild.get_channel(channelID)
if not channel:
return await message.channel.send(f'{author.name} has leveled up to level {level}!')
await channel.send(f'{author.name} has leveled up to level {level}!')
await self.bot.db1.commit()
Does anyone know what is wrong?
Where'd you get that info?
Do you have WAL mode turned on?
what is that? how do i check?
Consider using asqlite instead of aiosqlite, it automatically turns this on and does a few more things to work smoother
thank you!
python slowly drives me crazy with it's capital sensitivity 💀
!intents
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.
I don't know of any mainstream language that is insensitive to capitalisation.
anyone able to assist with this?
What have you got so far
absolutely nothing
well shouldnt say nothing
i followed a tutorial on yt and have a code but from what i can tell its just errors
A hands-on guide to Discord.py
(deleted link) this is the template code that i got from the video
Don't use this
That looks both like ChatGPT generated and youtube tutorial code at the same time
lovely
i know crap about coding and im attempting to learn it so i wouldnt really know tbh
ill read that tho, ty
This is to get started with bots, doesn't have anything regarding working with twitch. But when you are finished with that and have a running bot I'd be happy to explain the event that triggers the twitch part in Discord.
ok thank you
guyssssss i need hlpp
import discord
import os
from discord import Option
my_secret = os.environ['token']
bot_guilds = ["528480878100348928"]
bot = discord.Bot()
@bot.event
async def on_ready():
print("ready")
@bot.slash_command(guild_ids=bot_guilds)
async def sex(ctx, member:
Option(discord.Member,
"aaa",
required = True)
):
await ctx.respond("aaa: {} ".format(member))
bot.run(my_secret)
i want the guild id part not to be
someone can help me
can you elaborate? i dont really understand what you mean by i want the guild id part not to be
i mean to use this bot on multiple servers
then dont specify guild ids
yes yes
the command will be global
how
?
yes its should be
what must be
global
how can i
what library is that?
in py-cord the Interaction does not have .respond method
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
if it would be prefixed command it would be .reply but its a slash command so you get Interaction
okay guys so, i'm having a problem with the Database has no such attribute db, even thought i setted it up at beginning
File "c:\Users\User\Documents\GitHub\RP-Utilities\rpu_database.py", line 70, in search_default_character
documents = await self.db.characters.find_many([{'user_id': user_id}])
^^^^^^^
AttributeError: type object 'Database' has no attribute 'db'
thought i setted it at the beggining of the code
async def connect(self, connection_uri: str, /) -> None:
self.dev_client = motor.motor_asyncio.AsyncIOMotorClient(connection_uri)
if self.dev_client is not None:
self.db = self.dev_client.rpu_database
print("Database connected!")
else:
self.db = None
print("Cannot connect to Database!")
async def close(self) -> None:
self.dev_client.close()
but here when i declare from cog the things get like the error:
async def search_default_character(self, *, user_id: int, name: str | None, prompt_prefix: str | None) -> None:
documents = {}
if name:
documents = await self.db.characters.find_many([{'user_id': user_id, 'name': name}])
elif prompt_prefix:
documents = await self.db.characters.find_many([{'user_id': user_id, 'prompt_prefix': prompt_prefix}])
elif name and prompt_prefix:
documents = await self.db.characters.find_many([{'user_id': user_id, 'name': name,'prompt_prefix': prompt_prefix}])
else:
documents = await self.db.characters.find_many([{'user_id': user_id}])
return documents if documents else None
it erroers in the cog
but don't error in the db
at least it's what i think
ok so... did you call the method connect()?
in bot class yeah
can you show?
anyone know how to make 0auth2 for my bot
ive invited him to one server and I cant invite him to another
you have to create another invite from the bot page
like i create invite to invite my bot to servers from discord developer portal
class Bot(commands.Bot):
def __init__(self) -> None:
super().__init__(
intents=INTENTS,
command_prefix = prefix_setup,
case_insensitive=True
)
self.database = Database()
print("Bot Connected!")
async def setup_hook(self) -> None:
await self.database.connect("mongodb://localhost:27017")
self.db_loop = self.database.dev_client.get_io_loop()
for extension in EXTENSIONS:
await self.load_extension(extension)
await self.add_cog(PrefixCog(self))
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
here
mhm thats strange
did it print "connected" or something
it print "Database connected"
probably make it property instead
@property
async def db(self):
# same logic here
return db
in Database class

like this?
class Database:
def __init__(self) -> None:
self.dev_client: motor.motor_asyncio.AsyncIOMotorClient | None = None
async def connect(self, connection_uri: str, /) -> None:
self.dev_client = motor.motor_asyncio.AsyncIOMotorClient(connection_uri)
if self.dev_client is not None:
self.db = self.dev_client.rpu_database
print("Database connected!")
else:
self.db = None
print("Cannot connect to Database!")
@property
async def db(self):
return self.db
ok dont initialize it.
do this instead
class Database:
dev_client: motor.motor_asyncio.AsyncIOMotorClient | None = None
async def connect(self, connection_uri: str, /) -> None:
self.dev_client = motor.motor_asyncio.AsyncIOMotorClient(connection_uri)
if self.dev_client is not None:
print("Database connected!")
else:
print("Cannot connect to Database!")
@property
async def db(self):
if self.dev_client is not None:
db = self.dev_client.rpu_database
return db
return None

I tried
it doesnt work
you were lurking for straight 10 mins 💀



ayy robin wassup :)
helo
wait guess i got an idea
and if i parse the client of the database as property
actually
my bot needs the database
so guess i could pass the database class as property

like it's a mongodb
so my system generally use Database as object
but not directly database
!rule 9
Just ask your question
ok
i need a python discord bot, that uses roblox to make a condo generator in roblox
Is is possible to have 2 autocomplete fields for different parameters in 1 command?
People aren't really going to give you a bot
If you want to be given a bot you'd need to find a different server. People would be very helpful to you if you decide to create the bot yourself
I would suggest you do so, even just a little practice with coding will help open a lot of doors in the future
You'll also be able to fix bugs/add new features to your bot without having to pay for them
what server
okay
hey guys i have this error trying running my bot on my ubuntu server but my code works very well in local
and i installed discord.py and pip
Are the servers of both discord.py and Python the same on both the computers?
No the server is a laptop
And I have my pc that I use to connect to the laptop
Sorry, I meant the versions
I don't see any errors in that line, could you show the line around it?
I know you said it works well in local but I just want to doublecheck
Where do you live
Just a question
uh
Cuz I’m in France and it’s almost 2am so it’s not very an option to start my pc 💀
Why does it matter
later I’ll send you the entire code if u want
Yea it'll be better to ask again later when you can give more info to help troubleshoot
bro is going to make the whole city thought there is an airstrike
do u have requirements.txt?
its basically a file that tells the server that u need these library (or module idk) to work
Thx i know
But for me just installing via pip works well
but if u host it on the server
u cant pip install on the server right? 🤣
idk whats that
I have another that works very well
i use https://railway.app
Wth is this
u can host for 21 days every month for free (so there will be one week rest for ur exhausted bot)
and it comes with a database
Can host 1 year free w/ aws
Look three bots with one server
And for answer your question yes you can pip install on a server
Wait Comin back I’ll show u
W server
alright apparently railway faked me
💀
bro told me its free for 21 days every month
Look
I can pip install
On this bad boy 😎
And for making my bot running 24/7 I just used nohup
Ez amazon
How would I hide a slash command to only certain users? (ID specific)
I tried creating a check and it works, it just doesn't hide the command
Is it possible?
yes, you need to do it from the server settings
Not anymore, there has been change in plans since this August
;-;
the moment i came back to do some stuff bro changed policy 🥹
localhost
And this would completely stop users from seeing the commands? Do I have to do anything from my end?
I believe so, yes.
You shouldn't have to do anything code-wise
hey guys, just made this tutorial and thought it may help some people out.
https://discord.com/channels/267624335836053506/1139753110244434021
discord.py
@app_commands.checks.default_member_permissions(...)?
This just checks if they have the permission, they can still see the command
I was already shown the solution though
yeah i mean for multiple servers you have to do it manually kinda sucks lol
this is not how it looks like. the docs didnt lie about it tho. but when i used it it actually hides it entirely
while check.has_permissions doesnt
complicated
Docs doesn't say anything about hiding it

yeah it doesnt but when i tried it did lol
I can try
!d discord.app_commands.default_permissions is the correct decorator, but yeah it will hide based on whatever permissions are given once its synced
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
im definitely going to be using that if it does that
^^
isnt it default member permissions or something? did they change the name? lol
yeah ig
huh i cant recall seeing that attribute despite having looked at AppCommand a few times before
oh wait
Oh cool
Is there any way to do it by user ID though, where I can choose specific users? Or would I have to do that through the server settings
^ discord API doesn't support it at all
just give them a role with lower permissions than stated for the default permissions
Isn't going to work
I only want me and the servers owner to have access to the command
well just give server owner admin roles?
and urself
There are other people with Admin roles I don't want using it

that defeats the purpose of admin roles lol
shrug, you've hit a limitation of slash commands
Yeah, they can just do it through the server though
or use has_role
Not really, it's only 1 command
Wouldn't that require making a custom check?
He also want that slash command to be hidden.
I made a custom check with the IDs and it worked, it just didn’t hide the slash command
Yeah slash commands are not hidden like prefix i think
U need to do that from server settings
Instead of adding the ids manually u could have made it retrieve the server owner id itself incase a server owner changes
The bot is for a singular server so it doesn’t really matter to me ngl
I also might add more people to the list so I’m trying to keep track of it all
Hmm i see
For that u could have use has_role
Just give the role to the user who can use the commands
Well in the end it's up to you how u want to do it
I don’t have admin perms so
Look, there’s a ton of reasons it has to be by ID only
oh yeah cant the other admins change the override anyway?
anyone active right now?
Just ask your question and when someone is available they will answer
someone tell me how to delete all previous messages in a specifiq channel before bot arriaved
i want it like a event
What?
i want to clear an entire channel messages
wdym before the bot arrived?
make a clear command
i meant every messages that was sent in that channel before bot arriaved, i want them to get deleted after my bot arraived
wdym arrived?
Hello, everyone.
Hi
after my bot joined
hi
joined the guild?
ye
I feel like if I ask my question, I'll be talking out of turn.
just ask pros are here
well you have to do it with your bot. You cant just do it if the bot is not in your server
ofc ik that
but i need an example script with which functions and intents i can do that in ptyhon using discord.py
I'm fairly new to Python as a whole. I've created my chatbot and I have it listening to the channel I was testing in, but the message.content is always coming up empty. I know that the on_message event is getting called.
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
You need this intent to read messages
well i can show you how you can clear a channel when the bot joins
@client.event
async def on_guild_join(guild):
if guild.id == YOUR_GUILD_ID:
channel = client.get_channel(YOUR_CHANNEL_ID)
await channel.purge(limit=100)
That's what I thought I did with this:python intents = discord.Intents(messages=True, guilds=True) bot = discord.Client(intents=intents)
let me use that and see if that work ( after edit
Well, I don't see message_content being enabled there
That's a separate intent?
Yes? That's why it has a separate variable name
🤦
That did the trick
This was the first time I've ever had to deal with this API stuff and that sea of text was just so overwhelming.
didn't work for me
error?
nope
and show your code
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True # Enable message content intent
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.event
async def on_guild_join(guild):
if guild.id == 1035803076491214902:
print("working")
channel = bot.get_channel(1082691739183239258)
print("working")
await channel.purge(limit=100)
print('working')
# Run the bot using your bot token
bot.run(bot_token)```
it didn't even showed the first working
did you debug it a little?
haven't tried yet
?
this
async def on_guild_join(guild):
if guild.id == 1035803076491214902:
print("working")
channel = bot.get_channel(1082691739183239258)
print("working")
await channel.purge(limit=100)
print('working')```
is not even being executed
you debuged it?
ye
what did it print?
nothing ;-;
@bot.event
async def on_guild_join(guild):
print(f"guild id == {guild.id}")
if guild.id == 1035803076491214902:
print("working")
channel = bot.get_channel(1082691739183239258)
print("working")
await channel.purge(limit=100)
print('working')```
hey how is your code is so colorful....
!code
try and print something before the if statement
hmm
@bot.event
async def on_guild_join(guild):
print("IS THIS EVEN WORKING?")
if guild.id == 1035803076491214902:
print("Working")
channel = bot.get_channel(1082691739183239258)
print("Working")
await channel.purge(limit=100)
print('Working')```
didn't even print that ;-;
very weird
pretty weird ik
i dont know why its not working
hmm let me convert it to a command then
ok
AttributeError: 'NoneType' object has no attribute 'change_presence'
when i try to change my bot's status
i get this error
anyone knows ?
you have any other on_guild_join event registered
!e
None.change_presence
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | None.change_presence
004 | AttributeError: 'NoneType' object has no attribute 'change_presence'
im not that dumb 💀
well show your code then
let me run the code one last time then i show?
import discord
from discord.ext import commands
import asyncio
intents = discord.Intents.default()
intents.message_content = True # Enable message content intent
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def delete_messages(ctx, channel_id: int):
channel = bot.get_channel(channel_id)
if channel is None:
await ctx.send("Channel not found.")
return
while True:
try:
await channel.purge(limit=None)
await ctx.send(f'Deleted all messages in {channel.mention}.')
break
except discord.HTTPException as e:
if e.status == 429:
print("Rate limited, waiting and retrying...")
await asyncio.sleep(5) # Adjust the sleep duration as needed
else:
raise # Re-raise other exceptions
? didnt understand
whatever you try to run the .change_presence method on is None
no idea you never showed code
and where is that on_guild_join event?
i removed that command because i thought normal people wont find out what that means
that command name*
where is this code
!code
i already gave you the script ( entire script except the token
in what you sent me i dont see the on_guild_join event you have trouble with?
import discord
import responses
from discord.ext import commands
from discord import app_commands
# Send messages
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'Your Token'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
game = discord.Game("with the API")
await bot.change_presence(status=discord.Status.idle, activity=game)
@client.event
async def on_message(message):
# Make sure bot doesn't get stuck in an infinite loop
if message.author == client.user:
return
# Get data about the user
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
# Debug printing
print(f"{username} said: '{user_message}' ({channel})")
# If the user message contains a '?' in front of the text, it becomes a private message
if user_message[0] == '?':
user_message = user_message[1:] # [1:] Removes the '?'
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
# Remember to run your bot with your personal TOKEN
client.run(TOKEN)
here it is
why you create both Client and Bot instance?
u are right
i changed the name "on_guild_join" to "delete_messages" after the entire script is working
but now it wont trigger on guild join
its just a command now
fixed that duplication @slate swan
ik im working on it right now
why you have your whole code indented to a function
ok now gtg to make that command into event bye
what should i do ?
answer why you have it in a function
dont even know yk
its my friends code
i write games not bots, he is new at this and im tryna help
you get me right ?
does anyone know how to solve the 'no module named discord' error when I import discord
Did you install it?
why do i get a
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
in my reaction role, does it just mean my bot doens't have the perms to add a role to a user
