#discord-bots
1 messages · Page 303 of 1
I’m literally just mentioning it
and ur free to ignore what he says
Imma go ahead and block you
Alright buddy!
fr
think he too it too litterally
Is this the full trace back?
People take things too personally, I literally have no clue who he is
There are like 30+ users in this channel a day
It’s a common opinion as well, even has a tag in the discord.py server
ye
but if i must say i will disagree with ur opionin as a lot of bots have it and is just nice to have the name included but thats just my seeing
Is there an error?
this it
Something wrong with the json it looks like
Possibly when doing response.json()
Id print the text first, and see if it’s valid
I had the same error trying to use APIs
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
There is no json file
The response could be empty, or invalid
He’s requesting an API
i think tht i wrote conplete nonsense lol. im gonna rewrite it. thanks for the help, tho

then no data
and i'd suggest using aiohttp or some similar async lib for doing api calls
as synchronous lib can cause blocking
httpx is a good option
I need something that can change the colours on an image, for something like emojis
^
Ok so, I just figured out, you need to resync commands each time it joins a server, is there a way I can do that?
it wouldnt be recomended but you can use the event on_guild_joiniirc
@final iron how can u get up the docs (in d.py u can use ?rtfm)
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
ooh
Would this work
async def on_guild_join(guild):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await self.reload_extension(f'cogs.{filename[:-3]}')
print(f'Reloaded {filename[:-3]} cog after joining {guild.name}.')
except Exception as e:
print(f'Failed to reload {filename[:-3]} cog after joining {guild.name}. Error: {str(e)}')```
I prefer it
ye but you could get rate limited i think
why?
Sometimes there’s functions with the same/similar names
They have different use cases
I prefer this bot when I’m helping, as it’s clear what I’m referencing
ye this does give more info in discord
But when I’m searching for something r. Danny makes it easy
2023-09-16 06:12:55 INFO discord.client logging in using static token
[+] Utility Commands Loaded!
2023-09-16 06:12:56 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 95495f7802a483bd8fa3683f3991993d).
2023-09-16 06:13:38 ERROR discord.client Ignoring exception in on_guild_join
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
TypeError: on_guild_join() takes 1 positional argument but 2 were given```
yes
ok show whole class
class Solaris(commands.Bot):
def __init__(self):
# initialize our bot instance, make sure to pass your intents!
# for this example, we'll just have everything enabled
super().__init__(
command_prefix="s!",
intents=discord.Intents.all()
)
# the method to override in order to run whatever you need before your bot starts
async def on_guild_join(guild):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await self.reload_extension(f'cogs.{filename[:-3]}')
print(f'Reloaded {filename[:-3]} cog after joining {guild.name}.')
except Exception as e:
print(f'Failed to reload {filename[:-3]} cog after joining {guild.name}. Error: {str(e)}')
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await self.load_extension(f'cogs.{filename[:-3]}')
except Exception as e:
print(f'Failed to load {filename[:-3]} cog. Error: {str(e)}')
Solaris().run(TOKEN)```
why are you reloading all the extensions when u r joining a guild?
just reload the extension that has the thing u need to reload instead of all of them
there's only gonna be 3 cogs so it should be fine
but how do I fix this error
@vocal laurel
oh okay
where do I put it
before the guild param
self.guild?
It's working now
ok nice
thanks :)
np 😄
is worth adding owner commands for ro loading cogs or no?
I'll make a owner cog, and add them to it
ok sure
u should also try jsk
jishaku is a debugging and experimenting cog for Discord bots using discord.py@rewrite.
Note that this only works with Python 3.6+ and discord.py rewrite.
You can install it by running the following:
pip install -U jishaku
or
pip install -U git+https://github.com/Gorialis/jishaku
To get the cog running, simply do
bot.load_extension('jishaku')
You can see the source code yourself here: https://github.com/Gorialis/jishaku
A debugging and testing cog for discord.py rewrite bots. - GitHub - Gorialis/jishaku: A debugging and testing cog for discord.py rewrite bots.
just install jishaku
thne do self.load_extension("jishaku") inside setup hook but outside of for loop
I'm so confused
@vocal laurel
@vocal laurel check that, I'm getting errors for it
you are using bot.load_extension inside the class
I use self right?
try and see
still the same error?
Nope, self is not defined
show what u did
yes
!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/TY6Q @turbid condor
Still nothing
I fixed it, there was extra code at the bottom that was causing it to fail
That's the highest ping I've ever seen @turbid condor
13 seconds of lag 
I don't even know
how that happened
Uh @turbid condor I need help
I'm trying to put my files onto a server, and it's saying the ./cogs/ dosent exist
I'm using Diva Hosting, and yes I did upload the cogs
Is it because it's on a server? So it's different code to find files?
Could be
Ok nvm
I do, for this
bot.remove_command('help')```
I want it to work with my bot
Idk where to put it
In the super.init for Solaris class just do help_command=None
oh
I got invalid syntax
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.
nevermind, I forgot a ','
why remove the default help command?
so I can make my own
it's 7:41am, I haven't slept, I'm making little mistakes with my code lmao
FYI that's not how you do it
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command```
See the documentation: <https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#help-commands> for more details.
For migrating from old helpformatters: <https://discordpy.readthedocs.io/en/latest/migrating.html#helpformatter-and-help-command-changes>
A walkthrough on subclassing help:
<https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96>
what
that
that's the proper way to do it
would recommend reading up on the guide on how to do it
but why would I need to do the over complex way?
the "complex way" handles a lot of the stuff for you already. the way you are thinking of implementing it is more than likely hard coded. What happens if you have to hard code 100 commands with the names, examples, and descriptions?
Doing the subclassing method will quite literally save you a ton of work and all you need to do is to initally create your own subclass, write the code to format the way you like it, and dpy will handle the rest for you automatically
but that's learning something I have no clue of, I've only just started with cogs
tackle it at a later time. but what i'm saying is that you should use the subclass method instead of the way you were originally thinking of doing it
@bot.command()
async def buy(ctx, type, count):
guild = bot.get_guild(guild_id)
probot = guild.get_member(probot_id)
bank = guild.get_member(bank_id)
buier = guild.get_member(ctx.author.id)
if int(count) <= 999:
await ctx.reply("**عذرا**, اقل كمية للشراء هي 1000")
else:
if type == "flagged":
price = int(count) * 5000
tax = price / 0.95
await ctx.reply(f"تم ضبط البوت على تسليم التوكنات تلقائيا (هذه توكنات تحكم وليست اونلاين او اوفلاين)\n\n سعر {count} flagged هو **{price}**\n لديك 5 دقائق للتحويل")
await ctx.send(f"c {bank_id} {ceil(tax)}")
try:
await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == probot and str(price) in m.content and bank.mentioned_in(m), timeout=300)
except asyncio.TimeoutError:
await ctx.send("وقت التحويل انتهى [x]")
else:
await ctx.send(f"تم استلام طلبك. ستصلك رسالة في الخاص فيها {count} flagged\n {buier.mention}")
await buier.send("hi bb")
if type == "unflagged":
if count >= ufs:
await ctx.send(f"**عذرا**, الكمية المتوفرة حاليا هي فقط {str(ufs)} ")
else:
price = int(count) * 12000
tax = price / 0.95
await ctx.reply(f"تم ضبط البوت على تسليم التوكنات تلقائيا (هذه توكنات تحكم وليست اونلاين او اوفلاين)\n\n سعر {count} flagged هو **{price}**\n لديك 5 دقائق للتحويل")
await ctx.send(f"c {bank_id} {ceil(tax)}")
try:
await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == probot and str(price) in m.content and bank.mentioned_in(m), timeout=300)
except asyncio.TimeoutError:
await ctx.send("وقت التحويل انتهى [x]")
return
else:
await ctx.send(f"تم استلام طلبك. ستصلك رسالة في الخاص فيها {count} unflagged\n {buier.mention}")
await buier.send("hi bb")
else:
await ctx.reply(f"""عذرأ ، يرجي استعمال الأمر بشكل صحيح !
مثال :
!buy (flagged - unflagged) (amount)""")
@buy.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
await ctx.reply(f"""عذرأ ، يرجي استعمال الأمر بشكل صحيح !
مثال :
!buy (flagged - unflagged) (amount)""")
why when the time of wait for ends the bot make this action also
await ctx.reply(f"""عذرأ ، يرجي استعمال الأمر بشكل صحيح !
مثال :
!buy (flagged - unflagged) (amount)""")
you know the isinstance doesnt work like that if isinstance(error, commands.MissingRequiredArgument) or (error, commands.BadArgument):
how it works?
you are just checking if error is instance of MissingRequiredArgument or if (error, commands.BadArgument) this tuple resolves to True
which always gonna be true
if you want to check if its this or that type do this isinstance(error, Error1 | Error2)
if those are the errors you want to check for yes
the problem aint solved
also
the problem not from the error
its from the else
the bot join in this else someway
else:
await ctx.reply(f"""عذرأ ، يرجي استعمال الأمر بشكل صحيح !
مثال :
!buy (flagged - unflagged) (amount)""") ```
solved
can someone give me a fun command to add to the bot
make an economy system, and add taxes to your system
leave - makes that bot leave from the server 
and then calculate govt tax revenue, where a govt in this case is a server
the calcuatations are not that hard
Guys i have an question when i do in python an script i execute it but the bot command doesnt respond
And the perms are all set
And the bot is online
Show code
Wait im not home
Can anybody code me a command: .message (role) (number of days)
that would basically get all member from a specified role and get their messages counted
for the specified number of days
I need someone that knows nextcord dm me
Why choose nextcord? Is your bot made during the 2021 hiatus of dpy?
Get unix timestamp of what it'd be in set amount of time and store it in a db. Make a check on your bot that automatically goes through each one and checks if the role needs to be removed
Why are u using nextcord?
It has slash commands
Discord.py has it as well
How? I tried to make slash commands for months and nothing worked
In fact, all of the major discord features like dropdowns, modals, buttons, slash commands, etc all work
Remember yesterday, how should I go about inputting the data into the db
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Guys I have general question , I see many people jump into discord.py without knowing python , why?
Because they don't want to learn ¯_(ツ)_/¯
The why they come here to ask their dumb questions?
Bc they want to create dbots and get that clout without putting the effort to learn
@quick brook Ill change to discord.py if i get the slash commands working ill stay on discord.py
Ok
True
You can ask them 
Hmm
i feel like it's because of how simple the syntax is for discord python bots that they fail to see the amount of abstraction needed to make it simple so they just jump in without knowing python
Also those as well
woah, concurrency isn't basic tho
You need to know about asynchronous programming which is a intermediate topic
File "d:\\main.py", line 4, in <module>
from discord import commands
ImportError: cannot import name 'commands' from 'discord' (unknown location)
PS D:\> ```
discord.ext
tried
See docs
I don't see discord.ext here?
from discord.ext import commands
i removed it
Slash commands?
and it has the same error
from discord.ext import commands
I also said him this
Then you have a broken installation
oh
File "d:\\main.py", line 4, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
PS D:\> ```
oh sh im so dumb
try upgrading
pip install --upgrade
to use nextcord you have to uninstall discord.py
no i guess
Yea u need to uninstall nextcord if u want to use dpy
Ok now i did it and i ran it i got this error:
bot.load_extension(f"Cogs.{filename[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
But why ? It isn't that u can't keep multiple libraries?
Now with dpy, loading exts are now async. So you need to await them
Namespace issues. The forks are forked off of dpy 1.7.3 and conflict with the namespace of dpy
discord.ext.commands.errors.ExtensionFailed: Extension 'Cogs.economy' raised an error: TypeError: object NoneType can't be used in 'await' expression
@bot.event
async def on_ready():
print("BOT ONLINE")
for filename in os.listdir("./Cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"Cogs.{filename[:-3]}")
await bot.change_presence(activity=discord.Game(name="/help"))```
Is the await on the same line?
yesssssssssssssssss
I see
Instead of doing async setup in on_ready, or using a task which may lead to events being called before that task runs, you can overwrite Client/Bot.setup_hook.
For example:-
class MyBot(commands.Bot):
async def setup_hook(self):
print("Bot is starting")
await self.load_extension("my.extension")
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook
What is that
You can code together
I'm on mobile rn. Just put the code on GH and I'll fork and make a PR with the changes
You can edit it on mobile
It's hard to do it on mobile and I'd prefer to do it on my laptop instead
kk
Btw don't mind but u should not spoon feed
Yea I won't
I am sorry if my language is bad
It's fine
still cant fix it
stupid question but ive been reading the api and researching and everything and i just cant learn anything related to discord.py and all im trying to do is make it create a category + voice channel that nobody can join, any tips?
learning bot dev sounds impossible idek where to start
!d discord.Guild.create_voice_channel - you can specify the overwrites
await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel) except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel) instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
!d discord.Guild.default_role - This return the @everyone role, so you can set its connect overwrite to false in the said argument
property default_role```
Gets the @everyone role that all members have by default.
i've no clue how to use any of these, where can i learn from?
Click on the link in the embed to look at its docs
Demo:
await guild.create_voice_channel("some-voice", overwrites={guild.default_role: discord.PermissionOverwrite(...)})
Do someone know a good repo with a music bot ?
or a tutorial to make it for myself ?
hey, i am trying to get the profile picture of the bot the script is controling, but my code does not work:
pb = client.user.avatar_url
('ClientUser' object has no attribute 'avatar_url')
how can i fix this?
!d discord.ClientUser
class discord.ClientUser```
Represents your Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
it should be avatar.url
changed in 2.0+ I believe
whats the difference between on member remove and on member leave
Difference is that on member leave doesnt exist
Is there a way to check if a user is a bot from the message object?
Hey, how could I fix this error? I'm trying to make a role stript command where it takes a members roles away
@app_commands.commands.command(name="rolesript", description="nothing")
@app_commands.checks.has_any_role(owner_role, co_owner_role)
async def roe_stript(self, interaction: discord.Interaction, member: discord.Member):
for role in member.roles:
await member.remove_roles(role)
await interaction.response.send_message("done!")```
Fixed it, it is display_avatar now
!d discord.Message.author
!d discord.User.bot
Specifies if the user is a bot account.
Member.roles
A list of Role that the member belongs to. Note that the first element of this list is always the default
@everyonerole.
It's probably throwing an error trying to remove the everyone role from them.
hm, and how do I stop that from happening?
by making a if statement?
You need to get the role firs using get_role
What?
can't I just make a for loop for that?
Either skip the first element of member.roles or check each if each individual role is the default role
!e
roles = ["everyone", "some_role", "another_role"]
for role in roles[1:]:
print(role)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | some_role
002 | another_role
Ok
The way I've done it is like... for role in roles: if not role x: do the thing
I like this though
thanks it works now
instead of doing that just do for roles in member.roles[1:]: ...
Yes? That's just a pseudo code
how can i make a discord channel delete if no message has been sent in it in over 30 minutes?
Some sort of memory cache that keeps track of the last time a message was sent, and a task that checks it
Store the time of the most recent message and wait 30
Cute umbrella
Cancel the sleep task when a new message happens, restart it
That's what I would do
How could I pull a member's role with all of the role's ID?
Do a for loop over member.roles
this?
async for message in channel.history(limit=1):
time_since_last_message = (discord.utils.utcnow() - message.created_at).total_seconds()
if time_since_last_message > 1800: # 30 minutes in seconds
print(f'Deleting channel: {channel.name}')
await channel.delete()
break```
You could just use on_message
Yeah I know that but i'm trying to get the members role in a int
so member.roles.id?
No
ohhh
how?
Makes sense now
Have a dict where the key is channel ID and the value is asyncio.Task, in your on_message, check if there's an entry for it, if so, cancel the task, start a new one, and set it as the value
Hi I have a problem with a Discord BOT,
I have created a separate folder for each command and specified that in the main.py see picture.
However, the error always comes when I start the bot: 2023-09-16 17:43:17 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\knapp\OneDrive\Onedrive ALT\Desktop\Coaching_BOT_V1\main.py", line 22, in on_ready
await load_cogs()
File "C:\Users\knapp\OneDrive\Onedrive ALT\Desktop\Coaching_BOT_V1\main.py", line 16, in load_cogs
await bot.load_extension(extension)
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.create_coaching_zone' raised an error: TypeError: object NoneType can't be used in 'await' expression
Can you show the extension's setup function?
yo catty sup :3
If you're using discord.py, the setup function needs to be async
Hiii 🐈

you mean this?
async def load_cogs(): initial_extensions = ['cogs.create_coaching_zone', 'cogs.delete_coaching_zone', 'cogs.helpme', 'cogs.clearall', 'cogs.member_update'] for extension in initial_extensions: await bot.load_extension(extension)
no.
No, from the extension file
Or cog, if that's how you call it
f`rom discord.ext import commands
class ClearAll(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command(name='clearall')
@commands.has_role("Leitung") # Nur Benutzer mit der Rolle "Leitung" können diesen Befehl verwenden
async def clearall(self, ctx):
channel = ctx.channel
async for message in channel.history(limit=None):
await message.delete()
# Logge die Aktion
await ctx.send('Alle Nachrichten im Kanal wurden gelöscht.')
def setup(bot):
bot.add_cog(ClearAll(bot))`
you must add setup function in extension file [seems like u did or it would raise exception] maybe the setup function is the impasta here 
!d discord.ext.commands.Bot.add_cog
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a “cog” to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group) then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog)’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load) method will be propagated to the caller...
Change the setup function to an async function and await the add_cog method
its coro and the setup function needs to be async as well
async while True 💀
Seems like the cog is not loaded
There is some error in create_coaching_zone.py
So if you are using a for loop it gets terminated when this error occurs so fix that first or try loading this cog seperately
do th same thing to all other extensions
Yea that's the first one in the list for the loop
fix the setup function in every extension/cog
hey. is it possible to split comment every N words here?
@client.command()
async def ytcom(ctx, *, comment: str):
url=f'https://some-random-api.com/canvas/misc/youtube-comment?avatar={ctx.author.avatar.url}&username={ctx.author.name}&comment={comment}'
cant figure out how to do it
how to know the servers that bot in them?
U can use bot.guilds to get a list of the guilds the bot is in
I want to get the links
The invite links?
yes
For that your bot needs to have permission to create links in them
How can I fix this error with aiosqlite?
@app_commands.commands.command(name="unrole-stript", description="nothing")
@app_commands.checks.has_any_role(owner_role, co_owner_role)
async def unroe_stript(self, interaction: discord.Interaction, member: discord.Member):
async with self.bot.db2.cursor() as cursor:
await cursor.execute("SELECT role FROM user =?", (member.id))
role = await cursor.fetchone()
await member.add_roles(role)```
U need to get the default channel after that for every guild and then generate an invite using create_invite
https://discordpy.readthedocs.io/en/stable/api.html#discord.TextChannel.create_invite
Read this. And it's a question for #databases next time.
Okay thanks
thats not working, can you give me example?
That's very privacy breaching. Have you read the legal documents of Discord?
server invite link is a privacy breaching?
Creating server invites for any server your bot is in without the consent of the server owner is privacy breaching, yes.
Consider someone adding the bot in order to spam his commands or for sabotage purposes whatever. How is this thing illegal when it is present in the docs + when the server owner adds the bot, he will agree to give the bot the ability to create a link, and therefore this is considered approval.
No. Using your bot as a tool to create a backdoor for a Discord server and give yourself an invite is breaching their terms of services and privacy policy.
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
you said if the server owner accept its ok so when he add the bot he accept for this permission
And that has been the case for years
No.
You don't seem to understand
The command that may use that permission can be used by people within the server. There it's obvious they can use it as they are already members of the server. You, you are just inviting yourself to a server which you don't belong to nor have been asked/invited to join.
It's not because your friend gives his keys to his home to their family that you can force their family to give you the keys of his house.
This could be against tos if the server isn't an open server
like this python server
Doubt any bot has all servers open servers listed in server discovery...
Clearly wants links to every single server the bot is in. That's privacy breaching and you won't get help to breach Discord's terms.
It makes me feel like the Discord server is a bedroom for married couples 😂
There are servers that are not for everyone like a guild server
Or a company's server
If you have an issue with a server that is misusing your bot, make your bot leave it and then add it to a blacklist so that it will always leave it once the bot gets invited there. As simple as that
You don't need to be privacy breaching and join their server. You'll end up getting banned from Discord
Do it if you want, we won't help you. Then enjoy the Discord ban you'll get
how do I know thats he do without see the server?
You can log commands he's using
That's what logs are for
You can log the arguments they give in your commands
You have everything you need, you don't need to join any server to know what's happening there
I'd just put a limit on commands that can be used in a second or something similar
Rather then going to a server and seeing myself
by the way, How can I benefit from the create invite feature (for members inside the server)
I won't recommend that feature
Since some ppl don't want everyone to create an invite to a server
everything is ilegal for you?
And even if they wanted they could give everyone perms and they can just do it by clicking a + icon
I am trying to make my bot to run two files together in pycharm, but when the one fileruns, the other one doesn't. What should I do?
Use cogs
What's that?
You made me a gang leader and a spy just to try to learn an advantage in discord.py lol
thats legal so help me pls
a basic cog + extension example for discord.py v2. GitHub Gist: instantly share code, notes, and snippets.
I just told u it's not needed when creating it by using the discord ui is better
And if u still want to do it u can check the link i sent
That explains everything
Then read the docs
aint work
maybe I used them wrong so I asked him to give me an example and thats the answer
Instead of asking for example show what u did
And i don't think there is any need for an example if you read the info
💀
@bot.command()
async def invite(ctx):
link = await ctx.guild.create_invite()
await ctx.send(link)
It tells you what type of data it needs and describes what it does lol
Wonder why it didn't work
Capitalize guild
Read second line of the attachment i sent
Yea ik
Welp there isn't anything that needs explaining then i think
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite) to do this.
ah
Good afternoon
!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.
Is this the proper way to do this?
https://paste.pythondiscord.com/7QOA
`import discord
from discord.ext import commands
import config # Importiere deinen Token und andere Konfigurationen aus config.py
import tracemalloc
Starte das Tracemalloc-Modul
tracemalloc.start()
Erstelle den Bot mit dem gewünschten Präfix und Intents
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
Asynchrone Funktion zum Laden der Cogs
async def load_cogs():
initial_extensions = ['cogs.create_coaching_zone', 'cogs.delete_coaching_zone', 'cogs.helpme', 'cogs.clearall', 'cogs.member_update']
for extension in initial_extensions:
print(f"Loading extension: {extension}")
await bot.load_extension(extension)
Event: Bot ist bereit
@bot.event
async def on_ready():
# Lade die Cogs, wenn der Bot bereit ist
await load_cogs()
print("Bot ist bereit.")
... Weitere Bot-Event- und Setup-Code hier ...
Starte den Bot mit dem TOKEN aus der Konfigurationsdatei
if name == "main":
bot.run(config.TOKEN)`
create_coaching_zone.py
`import discord
from discord.ext import commands
class CreateCoachingZone(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def create_coaching_zone(self, ctx, category_name):
# Überprüfe, ob der Benutzer die Rolle "Leitung" hat
if "Leitung" in [role.name for role in ctx.author.roles]:
try:
# Erstelle die Kategorie
category = await ctx.guild.create_category(category_name)
# Erstelle die Textkanäle in der Kategorie
await category.create_text_channel("coaching-chat")
await category.create_text_channel("coaching-info")
# Erstelle die Sprachkanäle in der Kategorie
await category.create_voice_channel("coaching-voice")
await category.create_voice_channel("coaching-listen")
await ctx.send(f'Die Coaching-Zone "{category_name}" wird erstellt.')
except Exception as e:
await ctx.send(f'Ein Fehler ist aufgetreten: {e}')
else:
await ctx.send('Du hast nicht die erforderliche Rolle "Leitung", um diesen Befehl auszuführen.')
def setup(bot):
bot.add_cog(CreateCoachingZone(bot))`
There is still the error : 2023-09-16 20:23:27 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\knapp\OneDrive\Onedrive ALT\Desktop\Coaching_BOT_V1\main.py", line 23, in on_ready
await load_cogs()
File "C:\Users\knapp\OneDrive\Onedrive ALT\Desktop\Coaching_BOT_V1\main.py", line 17, in load_cogs
await bot.load_extension(extension)
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\knapp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.create_coaching_zone' raised an error: TypeError: object NoneType can't be used in 'await' expression
https://discordpy.readthedocs.io/en/stable/migrating.html#command-extension-changes
setup() has to be an async function and bot.add_cog() needs to be awaited
AttributeError: 'User' object has no attribute 'roles'
staff_roles = [727152007009271822, 710242627089596459, 710241598348329080]
author_roles = [role.id for role in message.author.roles]
if any(role_id in author_roles for role_id in staff_roles):
return
How can I fix this?
ignore the message if it doesnt come from any guild? or alternatively check that the message guild is the same guild that has your staff roles
It's from the same server
seems odd that you'd get a User object if the message wasn't in DMs...
Here is the full code:
https://paste.pythondiscord.com/LIBA
are you 100% sure its not just triggering from a DM message? and what intents do you have enabled?
Yeah,
Traceback (most recent call last):
File "C:\Users\Gamer\Downloads\blitzcrank\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Gamer\Downloads\blitzcrank.py", line 387, in on_message
author_roles = [role.id for role in message.author.roles]
AttributeError: 'User' object has no attribute 'roles'```
author_roles = [role.id for role in message.author.roles]
INTENTS = Intents.all()
can you print out message.guild
Yes, that is the name of the Discord server 🙂
Something is wrong with the code
seems fine to me besides the lack of a filter for direct messages
unless its a discord or library bug...
I don't need to filter of direct messages. This is only dedicated for a few specific channels
I've run into a problem before with similar code where it wants to pull the user profile instead of the member profile
What is the solution here?
hmm have you changed anything about your member cache?
I think I added an if statement for my situation, if author is a user and not member, continue
can anyone help me? I can't get this imported
seems like py-cord syntax, were you intending to use that library instead of discord.py?
yes
Installed discord.py and followed pycord tutorial maybe?
What did you install with pip
No, how would I even do that?
if any(role.id in [insert role id list here] for role in message.author.roles)
this worked for me
with the member_cache_flags parameter of client, but thats probably not a problem if you didnt change anything
the issue is message.author being a user, so this seems equivalent

how do i get the bot object from inside a cog? i get it in the init of the cog but how to i grab that from a class later on
class Stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
class statsview(discord.ui.View):
def __init__(self, interaction:discord.Interaction, bot):
super().__init__()
self.bot = bot```...?
idk how to get bot into there lol
well if you have an interaction you can use interaction.client for that
but dont define classes inside your cog, thats just unnecessary
oooo ok forgot about that
for example: ```py
class MyView(discord.ui.View):
def init(self, bot):
super().init()
self.bot = bot
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command()
async def my_command(self, interaction):
view = MyView(self.bot) # or interaction.client
await interaction.response.send_message("Hello world!", view=view)```
so i really only need to put commands themselves in the cog? all my buttons and views can be outside it? lol
whoops
yup
well, im not gonna touch the one i just finished yesterday because well... it works right now.
good to know on the next one lmao
It's not installed by you
And it would be very hard to install it, because it doesn't exist
...
It was merged into interactions
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
can't send raw components
What
What
i guess its not the best one then
Are you trying to be a dpy fork shill?
What uni do you attend?
why do you ask 😭
I wanna learn so
why is it relevant 💀
Hi,
when using
bot.get_guild(guildID).roles
it gets a
SequenceProxy(dict_values[<Role id=676878804001488927 name='Server Booster'>,<Role id=1027164181419532341 name='Groot'>])
how do i get the IDs of the roles in a seperate list?
!d discord.Guild.roles
property roles```
Returns a sequence of the guild’s roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
you can create simple list comprehension to do that
because when i iterate over it get the name instead
what did you try?
cause it has Role objects
printing a role object does indeed show its name
when u print it prolly coz of __repr__
print(key, "\n")
str(x)
Returns the role’s name.
to acess id use .id
key.id
oh, worked thanks a lot
Likely because you haven't synced your commands
I mean that you haven't synced your commands like you did for the first time
Like you did to get your commands to show the first time
Then use your browser
To search how to sync commands with discord.py
No.
Then you haven't bothered even searching
Which is understandable as people here for some reason want to be given everything and don't search
!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.
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
dpy is an advanced library, and you need to know advanced concepts before you can start
If you don't even take the time to search for that, you won't go far
It's not meant for beginners at all
guys is it possible to make a bot run a program using the os lib?
Did you actually do it or copy pasta 
Look the 2 embeds above and you know it
Apparently the library isn't that hard so shouldn't be hard to know with the 2 embeds
Learn OOP python then.
Or click the google link and there's an amazing first result which has ready to use code to copy paste, you should be used to that by now
is pycord for discord bots?
Maybe a bit more clear
yes ik im boring af
py-cord yes.
thanks
Compares Discord libraries and their support of new API features
no
There are quite a lot of libs for making bots
py-cord is for Discord bots.
App commands work differently from message commands, they're handled mostly on Discord's end. Discord just tells your bot when someone successfully triggers a command.
In order to do this, you need to register your commands on the command tree then tell discord they exist by syncing with tree.sync.
Commands can be registered on the tree either as a global command or as a guild-specific command, and must be synced to the same scope they are associated with in the tree.
When you sync, you are telling Discord about the commands you currently have for a particular scope.
To sync global commands: await tree.sync()
To sync guild commands: await tree.sync(guild=guild)
Guilds must be either a Guild object or a discord.Object with the guild's id.
It may help to think of the tree as a dict like this.
{
None: [global, commands],
guild_one: [guild, one, commands],
guild_two: [guild, two, commands]
}
copy_global_to will copy [global, commands] and add them to the commands for the guild you pass.
This is only done locally, you must still sync.
All commands are global by default. There are a few ways to make them guild-specific:
@app_commands.guilds()decorator on anapp_commands.Groupsublcass or@app_commands.command()guild/guildsin@tree.command()guild/guildsinbot.add_cog, only if the cog is aGroupCogguild/guildsintree.add_command, not typically used
A common practice for syncing is to pick a specific guild for testing and run tree.copy_global_to(guild=guild) then tree.sync(guild=guild).
When you're done testing, tree.clear_commands(guild=guild) then tree.sync(guild=guild).
When you're ready to publish your commands, tree.sync().
?tag umbras sync command makes this flow easy using !sync *, !sync ^, and !sync, respectively.
?tag sync - why you shouldn't auto-sync
?tag whensync - when you should sync
?tag umbras sync command - a prebuilt sync command
Funny thing about Pycord is that
- The repository is named pycord
- The import is discord
- The package name is py-cord
Yeah maybe don't share that here....
oh ok
i could send it to my friend and let him install python and i can control his pc >:)
jkjkjk i wont
And get your account banned, indeed ggs
Much success
i stole that idea from no text to speech
And he stole it from already existing projects and whatever else
Not like he found out that on his own 
how can i die
May be worth staying on topic and following the #rules
no
no also my mom makes cookies
so i dont need urs
nuh uh mom and grandma cooking better 🔥🔥🗣️
money dosent buy happiness
no i can buy linux atleast for free
no
@slate swan stop talking or u gay
ok
<@&831776746206265384> thx ^
what
wat is a neocities
how to sync :
- step 1 : sync
!mute 1135704908373446716 
:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1694906185:f> (1 hour).
if pycord's commands work in a similar way to discord.py's, then it should be a case of just putting the tree.sync() in some sorta on_ready function
i'm having a look at the docs rn
They got way more than enough information to do it if you check above
pycord shoves it on_connect
by default
How do I pass a database cursor into a cog?
Or do I need to make a new pool for each cog
I just store it as an attr on mine, and then within the constructor of the cog, get it using self.bot
How do I store it as a bot attribute
Within your ctx to create the pool, you need to just set an attr (self.pool = pool) and then you can access it from there
Oh alr thanks
Np
U can't
Dpy only supports python 3.8+
uh oh i was trying to "hack" my vm using a discord bot
and the vm has windows 7 installed so thanks
i will now need windows 10 iso
Just use linux
but the script i made to "hack" the devices are windows commands
i will risk myself running it on the real machine then.
it dosent "hack" it just logs off and reboots and shuts down and alot of funny stuff
see ya
NO WAY THE SCRIPT I MADE WORKED
if by stateless views you mean views that have static custom ids and no per-message state, that particular situation is easily supported by dpy: ```py
class MyView(discord.ui.View):
@discord.ui.button(custom_id="football", ...)
async def football(self, interaction, button):
await interaction.response.send_message("🏈 ")
@client.event
async def setup_hook():
client.add_view(MyView(timeout=None))``` dynamic custom ID views however are in design hell last i checked, so the best you can do is hack together something with on_interaction and maybe View._dispatch_item()
see also: hangman
bot/cogs/games/hangman.py lines 291 to 297
# Create view to handle interaction
view = HangmanView.from_match(m)
item = view.children[int(m.group('keyboard'))]
# NOTE: referenced from ViewStore.dispatch
item._refresh_state(interaction, data)
view._dispatch_item(item, interaction)
view.stop()```
go ahead?
real
currently in need of help , is there any documentations for user updates for user banners
@commands.Cog.listener()
async def on_user_update(self, before, after):
if before.avatar != after.avatar:
pfp_url = after.avatar.url
pfp_doc = pfps_collection.find_one({'member_id': after.id})
if not pfp_doc or pfp_doc.get('pfp_url') != pfp_url:
pfps_collection.update_one({'member_id': after.id}, {'$set': {'pfp_url': pfp_url, 'timestamp': time.time()}}, upsert=True)
# snippet
if user.banner is not None:
banner_url = user.banner.url
banner_doc = banners_collection.find_one({'member_id': after.id})
if not banner_doc or banner_doc.get('banner_url') != banner_url:
banners_collection.update_one({'member_id': after.id}, {'$set': {'banner_url': banner_url, 'timestamp': time.time()}}, upsert=True)
# snippet
except:
pass
I just got off to get on my phone and realizing I deleted a useless part of the code , still have no idea of what the documentations are for before banner
no, this is not what i meant 😔
but yeah, doing something hacky wucky you can already create them ig
Guys, Can I make a discord bot that controls a computer like when I type /runcmd it opens cmd?
!d os.system , close to it
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait).
why would u do that if thats like exposing ur computer to discord
its just a expirement i wanna try
does any1 knows why when i try to use my bad as admin it says you dont have admin for the purge command
@bot.tree.command(name="purge", description="Purge a specified number of messages.")
async def purge(interaction: discord.Interaction, amount: int):
member = interaction.guild.get_member(interaction.user.id)
if member is not None and member.guild_permissions.administrator:
if amount <= 0:
await interaction.response.send_message("Please specify a valid number of messages to purge.", ephemeral=True)
else:
await interaction.channel.purge(limit=amount + 1)
await interaction.response.send_message(f"Purged {amount} messages.", ephemeral=True)
else:
await interaction.response.send_message("You do not have the necessary permissions to use the purge command.", ephemeral=True)
this is the error:
Traceback (most recent call last):
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\bot.py", line 60, in purge
if interaction.author.guild_permissions.administrator:
^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
show line 60 of bot.py file
if member is not None and member.guild_permissions.administrator:
then save the file and run the bot again
i did but even tho i have admin it says
You do not have the necessary permissions to use the purge command.
to check for permissions you should most likely use .has_permissions checks
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions).
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
it has an example usage ^
alr thx
wait now i get this error
Traceback (most recent call last):
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\bot.py", line 61, in purge
if interaction.author.guild_permissions.administrator:
^^^^^^^^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\joshk\OneDrive\Bureaublad\DextenOnTop\myenv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
code:
@bot.tree.command(name="purge")
@app_commands.describe()
async def purge(interaction: discord.Interaction, amount: int):
if interaction.author.guild_permissions.administrator:
if amount <= 0:
await interaction.response.send_message("Please specify a valid number of messages to purge.", ephemeral=True)
else:
await interaction.response.send_message(f"Purged {amount} messages.", ephemeral=True)
await interaction.channel.purge(limit=amount + 1)
else:
await interaction.response.send_message("You do not have the necessary permissions to use the purge command.", ephemeral=True)
as it tells you
Interaction does not have author
it has .user
wdym
i mean you already used it?
member = interaction.guild.get_member(interaction.user.id)
its your code
interaction**.user**
so i have to do .author?
how can I ignore the actions of all bots on the server? I have a condition that ignores only the bot itself, but not others
didnt i just say it does not have it
use .user instead
if message.author == self.bot.user:
return
ight
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot)
bot
Specifies if the user is a bot account.Type
bool
do you know what to do with that
thanks
How can I filter out direct messages?
https://paste.pythondiscord.com/4QOA
Traceback (most recent call last):
File "C:\Users\Gamer\Downloads\blitzcrank\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Gamer\Downloads\blitzcrank.py", line 389, in on_message
if any(role.id in [727152007009271822, 710242627089596459, 710241598348329080] for role in message.author.roles):
AttributeError: 'User' object has no attribute 'roles'```
@slate swan Can you help out?
You need Member object to have roles
How do I do that?
message.author can be either User or Member
User if its DM
Member otherwise
So i would just do if message.guild:
It would make sure its not DM message
The messages was sent in a channel
Sorry. Can you show me an example? I'm confused
This doens't help
if not message.guild:
return```
Since I'm getting the error when posting in the channel
So I have to start the code with:
@client.listen()
async def on_message(message):
if isinstance(message.author, discord.Member):```
Why is that? I'm still confused 😄
@slate swan I changed it to:
@client.listen()
async def on_message(message: discord.Message):```
and it works fine
This would make sure author is a Member
And what about:
@client.listen()
async def on_message(message: discord.Message):```
Wouldn't that make sure it only triggers messages from a channel and not DMs = this would mean that there is a Member
why would it?
Because of message: discord.Message
it changes nothing about it being only from servers
thats just a typehint
Well for some reason that solve the issue as well?
nope, its just a typehoint
use a conditon to check if the channel instance is DMChannel
message.guild is None
pro
Magic type hints saga
you can either check if guild is None or assert for Member type too @young dagger this will make sure its not from dms
def webhook_spammer():
clear_screen()
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "webhook.txt")
if os.path.exists(file_path):
with open(file_path, "r") as file:
new_webhook_url = file.readline().strip()
else:
print("The 'webhook.txt' file does not exist in the script's directory.")
return
guys why it says i dont have that
data/webhook.txt
async def on_message(message: discord.Member): right?
we ont help with that since its againt discord tos
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
bro its only webhook
im just testing something why i cant search for the file
it just says no dicionary for some reason
didnt i say it clear we wont help with such project?
no why would it be correct
because u dont 🤓
You want something like this
down, learning web dev? or just an intermediate
i know react quite now just trying to do bot dashboard with next
def webhook():
clear_screen()
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "webhook.txt")
if os.path.exists(file_path):
with open(file_path, "r") as file:
new_webhook_url = file.readline().strip()
else:
print("The 'webhook.txt' file does not exist in the script's directory.")
return
``` IS A MALCIOUS PROJECT? BAHAHAHHAHAHA
open dir file is malcious
oh gg, gl
yes, spamming discord api is against ToS?
blud renamed function name xd
and?
Didn't even delete the old one lmao
The error message says the file doesn't exist. Maybe make the file exist
this prob shouldnt take long, its really quite easy fr, just the css the annoying part takes a bit, backend part is in our side xd
tru
well im kinda worried about making it work with actual bot script
bot is in py?
yeah
ye i spam everyone
nig i need perms to do that also not that its useless.
I want to make a bot dashboard
idek where to start tbh
i thought about making it how python discord does so add dashboard as dependency in docker compose but i dont really get how they share a database between or even if they do that
hmm, maybe connect the bot to the api, or just connect the database to the api

currently i understand it as database is on site project and they send data to it via api
at least i thought like that before i saw postgres service https://github.com/python-discord/bot/blob/main/docker-compose.yml#L12-L24
docker-compose.yml lines 12 to 24
postgres:
logging : *default-logging
restart: unless-stopped
image: postgres:15-alpine
environment:
POSTGRES_DB: pysite
POSTGRES_PASSWORD: pysite
POSTGRES_USER: pysite
healthcheck:
test: ["CMD-SHELL", "pg_isready -U pysite"]
interval: 2s
timeout: 1s
retries: 5```
you could do that too
wait.
does it just connect to the same database?
all credentials are the same
yeah, it should
wait
how can we have two connections
so the site package, gets the connection url as varriable and connects to it
meh forgor how postgres works
maybe, they connect via url directly, tho its really bad i m pretty sure, because public will be able to see the headers / payload via chrometab
yeah i think i get it so in order to run site package you need to aquire it with database url to connect to it
needs a proper authorization
which python bot serves and shares it with site
i dont even know where i should ask about it
django + some other python framewoek
it is
its python discord they were forced to
you could directly connect the bot object to the app
?
;-;
i meant to say, if you make the dashboard in py, then you can easily mount the bot to the app
but i aint making it in python
but for nextjs seems hard to me

Sup guys
sup
Is there any way to not trigger the code at all if DM?
@client.listen()
async def on_message(message):
print("Triggered")
if isinstance(message.author, discord.Member):```
After that isinstance check it filters out DMs
I did
How do I do that?
Will that filter out the DMs?
yes
down 🥣

Thanks @slate swan
🤫

I love soup

I just find it a bit annoying that you can't filter out DMs the same way you can with commands and @commands.guild_only()
commands.guild_only() is simply
if message.guild:
return True
Can I make my own decorator with the same logic?
yeah you can make your own check though
of course
just put the code you used to check dm and exit the function inside the decorator
You basically have to make a whole function for your custom decorator lol
I think the docs have an example of that to check if the person using slash command is_me
Maybe this:
def is_guild_member():
def predicate(ctx):
if not isinstance(ctx.author, discord.Member):
return False
return True
return commands.check(predicate)
@client.listen()
@is_guild_member()
async def on_message(message):
### Code here ###```
if not isinstance(ctx.author, discord.Member):
return False
return True
=
return isinstance(ctx.author, discord.Member)
:)

From the examples online:
class NoPrivateMessages(commands.CheckFailure):
pass
def guild_only():
async def predicate(ctx):
if ctx.guild is None:
raise NoPrivateMessages('Hey no DMs!')
return True
return commands.check(predicate)
@bot.command()
@guild_only()
async def test(ctx):
await ctx.send('Hey this is not a DM! Nice.')
@test.error
async def test_error(ctx, error):
if isinstance(error, NoPrivateMessages):
await ctx.send(error)
Interesting, thanks
or you could sum that all up with an if-else
Lol
Hey uh, I'm looking to make slash commands with my current cog setup, I just don't know how to make the hybrid commands for slash and prefix commands
Is it possible to run my bot 24/7 for free when my pc is turned off?
for free, i doubt it you need to buy some hosting
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
There's a couple free hosting spots but its not really beginner friendly. Like oracle vm or aws vm
Diva Hosting is a good option for hosting
Haven't tried them, actually just recently heard of them
I would provide a link, but it may be against rules so I'm not sure
you get not even half of cpu
yeah
I mean... you don't need a lot for a discord bot lol
everything depends on scale
If you're looking for free hosting, I assume you're on the lower 10% of the scale
it could be good enough to start
yeah for beginner might be
though we don't know the network settings
I run mine from my phone 
do they use shared IPs?
import requests
from bs4 import BeautifulSoup
import discord
from discord.ext import commands, tasks
def get_follower_count():
URL = "https://www.instagram.com/redacted"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
meta_tag = soup.find("meta", attrs={"property": "og:description"})
content = meta_tag.get("content")
followers_count = content.split(",")[0]
return followers_count
intents = discord.Intents.default()
intents.guilds = True
intents.messages = True
intents.message_content = True
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 setup(ctx):
guild = ctx.guild
category = await guild.create_category("Social Feed")
follower_count = get_follower_count()
voice_channel = await category.create_voice_channel(f"{follower_count}")
await category.set_permissions(guild.default_role, view_channel=True, connect=False)
await voice_channel.set_permissions(guild.default_role, view_channel=True, connect=False)
await ctx.send(f'Category "{category.name}" and voice channel "{voice_channel.name}" with the ID "{voice_channel.id} "created.')
@tasks.loop(minutes=1)
async def update_followers():
guild = bot.get_guild(redacted)
channel = bot.get_channel(redacted)
follower_count = get_follower_count()
voice_channel = await guild.get_channel(voice_channel.id)
await voice_channel.edit(name=f"followers {follower_count}")
await channel.send(f'Follower count updated\nCurrent followers: {follower_count}')
bot.run('redacted')
this is my code, but @tasks.loop doesnt seem to work properly, im new to this so i'd appreiate some help (2 days now)
What do you mean doesnt seem to work properly?
It's not starting?
tasks.loop just wont work like, nothing happens
my command works perfectly the channel gets created and all but the update_followers just doesnt do anything
It's just update_followers.start()
But do it in bot.setup_hook (just override it and put that line in there)
bot.setup_hook?
Ye
Define an asynchronous function that takes the bot as its sole argument (I think it goes like that) and do bot.setup_hook = that_func
alright, thank you
Nope
Ah then it doesn't take anything then
You don't need to add a bot parameter
What's the proper way to remove a persistent view
I would say if you need to remove persistent view then it shouldnt be persistent
Just disable it I imagine
Yea I think I've got what I wanted now
Nope nvm
If I stop() the view, it continues to be persistent after restart
Might have to just delete it entirely lol
Try .count()?
Message.reactions[0] should give you the first reaction on the post
Kinda running in a big circle lol
Try just if reaction.count >= 2
That should work.
That's a modal not an embed
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Giving me this error:
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)
Because you're apparently trying to from discord.enums import AppCommandOptionType which isn't a thing
What does that have to do with a modal
Why you put that in there then lol
Did you even read this?
This error has nothing to do with anything sent, it's you trying to import something that doesn't exist
script_dir = os.path.dirname(os.path.abspath(file))
data_dir = os.path.join(script_dir, "data")
file_path = os.path.join(data_dir, "bottoken.txt")
def get_token_path():
if hasattr(sys, '_MEIPASS'):
# Running from a PyInstaller bundle
base_path = sys._MEIPASS
else:
# Running normally
base_path = os.path.abspath(".")
token_path = os.path.join(base_path, "data", "bottoken.txt")
return token_path
# Use get_token_path() to retrieve the token file path
TOKEN_PATH = get_token_path()
if os.path.exists(TOKEN_PATH):
with open(TOKEN_PATH, "r") as file:
TOKEN = file.readline().strip()
else:
print("The 'bottoken.txt' file does not exist in the 'data' folder.")
exit()
bruh now its working on aws x)
script_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(script_dir, "data")
file_path = os.path.join(data_dir, "bottoken.txt")
def get_token_path():
if hasattr(sys, '_MEIPASS'):
# Running from a PyInstaller bundle
base_path = sys._MEIPASS
else:
# Running normally
base_path = os.path.abspath(".")
token_path = os.path.join(base_path, "data", "bottoken.txt")
return token_path
# Use get_token_path() to retrieve the token file path
TOKEN_PATH = get_token_path()
if os.path.exists(TOKEN_PATH):
with open(TOKEN_PATH, "r") as file:
TOKEN = file.readline().strip()
else:
print("The 'bottoken.txt' file does not exist in the 'data' folder.")
exit()```
idk why its not working...
it says i dont have it
even tho its straight infornt of my eyes
You don't have what ?
the txt file
yes
is it in the same file than your bot ?
yes
yes it is python
are you sure?
it is targeting the txt
yes
for me it's in .py and working very well
This relates to discord bots how exactly?
yeah try worth a shot
same thing
In the future, just open a help channel if you don't know what the topic is.
how do i see all the packages i've installed
pip list
because when i try to run my program i have this error :
Traceback (most recent call last):
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 9, in <module>
from discord import app_commands
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)
upgrade discordpy to latest
pip upgrade discord.py ?
pip install -U discord.py
i have an question when i use pyinstaller
it doesnt create the txt file
and when i use the main.py
its working
still the same error
Then you likely have multiple python installations
Then you haven't updated it
yes i did
So that's what I said, you have 2 python installations 
Uninstall Python 3.7 and just keep and use 3.11
discord.py doesn't support 3.7 anymore
but i still have the same error
Then you still haven't installed discord.py 2.x for Python 3.11
Just do python -V and see the version you're running
done this and it's taking me to the microsoft store for installing python 3.11
Get any version of python that is 3.8 or above
Then install/upgrade discord.py with python -m pip install discord.py
same error
Traceback (most recent call last):
File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 9, in <module>
from discord import app_commands
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\canai\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)
Print the discord.py version you have with print(discord.__version__)
And what is result of python -V
Python 3.11.5
!voiceverify
and what you get when you print out discord.__author__
i can't print my program doesn't work
You don't need a whole bot to print that
Pycord Development
2.4.1
Well... do you want to use discord.py or Pycord
Then uninstall Pycord? 
but idk why it's installed
Well you've definitely installed it once
and its not
PS C:\Users\canai\Desktop\bots\Partins> pip uninstall Pycord
WARNING: Skipping Pycord as it is not installed.
py-cord
just run this script ```py
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands discord-ext-slash"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
and now ?
and now run your bot script
👍
Bruh now i can't make a command for sending the modals
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
the class
And my command :
@client.tree.command(name="test1" , description="test1")
async def meme(interaction:discord.Interaction):
await interaction.response.send_message(Questionnaire())
The error :
Partin’s#0115 in Partin's: <Questionnaire timeout=None children=2>
c:\Users\canai\Desktop\bots\Partins\main_partins.py:168: RuntimeWarning: coroutine 'BotBase.process_commands' was never awaited
client.process_commands(message)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
its send_modal and not send_message
and error is related with process_commands
await <-- add this before client.proces...
worked but now i have only the error message : <Questionnaire timeout=None children=2>
send the whole traceback
no traceback
only this error
2023-09-17 19
29 INFO discord.client logging in using static token
2023-09-17 19
30 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 36e981c7a76b593ff261bde676b31586).
We have logged in as Partin’s#0115
Synced 15 commands(s)
Partin’s#0115 in Partin's: <Questionnaire timeout=None children=2>
No errors there
but why it is not sending the modal ?
Because you already got told
??
^

