#discord-bots
1 messages Β· Page 161 of 1
you can use bot.guilds in the command
it isn't internally ready*
the bot is ignoring the commands
yeah no not how python works
you need to acess the guild attribute of a discord.Member instance, not the class
that's what i did but you said
i used discord.Member.guild
i changed it to bot.guilds cus u said i could
@slate swan anyways my bot is not responding to any command, he is going online but not responding to any command
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
enable message_content intents and please do read the complete paragraph above
alright thank you
how can i delete the active server invite links? i can't find a solution
!d discord.Guild.invites
await invites()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns a list of all active instant invites from the guild.
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") to get this information.
!d discord.Invite.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Revokes the instant invite.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
And you need an instance, not a class
@client.command()
async def rdai(ctx):
await discord.invite.delete()
Also discord.invite is a module not a class
Get the invites from a guild?
to delete all the invite links
this is my code now and i'm getting this error
'member_descriptor' object has no attribute 'http'
import discord
from discord import Intents, Invite
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print('Online')
@client.command()
async def dai(ctx):
await Invite.delete(self=Invite)
This is way it is always recommended to know OOP before trying discord.py
yeah i know i'm just trying to find a quick solution to something in my server that i'm stuck on
It's just
guild = ctx.guild # get the guild
invites = await guild.invites() # get instances (objects) of invite class
Really?
How come when I make a slash command it takes forever to register? I made th e command yesterday
Did you sync the command tree
I just made a sync command I forgot to
@client.command()
async def dai(ctx):
guild = ctx.guild # get the guild
invites = await guild.invites() # get instances (objects) of invite class
await invites.delete```
is that it?
i don't need the list
You need to iterate over it then delete
i don't know how to do that that's why i'm here
Good, then don't get the invites 
You don't know how to use for in?
i used to but i haven't touched python for like 2 years or so
Guys is there a way for the discord bot to tell if a message contains a certain word
!for-else
for-else
In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.
Here's an example of its usage:
numbers = [1, 3, 5, 7, 9, 11]
for number in numbers:
if number % 2 == 0:
print(f"Found an even number: {number}")
break
print(f"{number} is odd.")
else:
print("All numbers are odd. How odd.")
Try running this example but with an even number in the list, see how the output changes as you do so.
use == or in
xd
I don't know what to say 
if "word" in message.content
!e
for num in [1, 2, 3, 4]:
print(num ** 2)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 4
003 | 9
004 | 16
Idk, just throwing stuff around
?
?
Alr thanks
I tried that before asking but it didn't work
I tried to use this command in order to delete all server invite links but it isn't working
I'll try again
dont forget to add colon after content: xd
π
is there another way to sync my slash commands without using the sync command
I just added sync command so I csnt sync it
Itβs been a whole day since I made these commands
I just sync it to one guild in the setup_hook then have a command for syncing globally.
Hey @spiral spoke!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
DEATH
import discord
import json
from discord.ext import tasks
import random
import datetime
intents = discord.Intents()
intents.guilds = True
intents.members = True
client = discord.Client(intents=intents)
# Load the JSON file
try:
with open('messages.json') as f:
messages = json.load(f)
except Exception as e:
print(f'An error occurred while opening the messages.json file: {e}')
@tasks.loop(time=datetime.time(hour=18, minute=10))
async def send_message():
try:
# Choose a random message from the list
message = random.choice(messages)
# Replace 'channel_id' with the ID of the channel you want to send the message to
channel = client.get_channel(1040599108408311859)
await channel.send(message)
except Exception as e:
print(f'An error occurred while sending the message: {e}')
@client.event
async def on_ready():
send_message.start()
# Replace 'token' with your Discord bot's token
client.run('')
I'm trying to make a discord bot with discord.py, the bot should send an automatic message every day at a specific time and minutes from a json file, but it doesn't send anything, nor does it show errors in the console, can someone help me ?
I mean like ```py
.. if "word" in message.content else ..
oh yea xd np
π
Might I just've made something like this...
from datetime import datetime
from discord.ext import tasks
from discord.ext.commands import Bot, Cog
class MyCog(Cog):
def __init__(self, bot: Bot) -> None:
self.bot = bot
self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
self.weather_loop.start()
async def cog_unload(self) -> None:
self.printer.cancel()
def get_next_date_at(*, hours: int = 0, minutes: int = 0, seconds: int = 0) -> datetime:
dtnow = datetime.now()
if dtnow.hour < hours or dtnow.minute < minutes or dtnow.second < seconds:
dt = datetime(dtnow.year, dtnow.month, dtnow.day, hours, minutes, 0, 0)
else:
tomorrow = dtnow + timedelta(days=1)
dt = datetime(tomorrow.year, tomorrow.month, tomorrow.day, hours, minutes, 0, 0)
return dt
@printer.before_loop
async def before_weather_loop(self) -> None:
await self.bot.wait_until_ready()
@tasks.loop()
async def weather_loop(self) -> None:
...
@bulker.after_loop
async def after_weather_loop(self) -> None:
self.weather_loop.change_interval(time=self.get_next_date_at(hours=6))
``` I tackled it like this, this is an example tough.
zamn
But agreed I don't get why it isn't some kind of kwarg for it.
my brain get an error :,))))
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
I recommend taking a look at Cogs and asynchronous coding.
the time kwarg
ok thanks :,)
what do i type here?
Hmm yeah, this is older code tough... or I made a mistake back then.. no telling now ig.
it was added recently in 2.0 π€·ββοΈ got unnoticed mb
@cloud dawn you forgot to help Wolt π
I don't forgor anything I was playing overwatch but then I remembered that the game kinda bad.
Lmao its fun, downloaded it just today (I am sure I will get bored in a day tho)
"its fun" you haven't played ow1 lol
Prolly

how do i get my bot to add 2 different reactions to one message?
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
well ive got that much to add one reaction
well do it again for 2 reactions?
await integration.delete(reason="AntiBot")
error : forbidden
2022-12-21 18
10 ERROR discord.client Ignoring exception in on_integration_create
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Other\Bots_For_Sell\Sys+Tick\bot.py", line 69, in on_integration_create
await integration.delete(reason="AntiBot")
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\integrations.py", line 153, in delete
await self._state.http.delete_integration(self.guild.id, self.id, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
You don't have perms prolly
i got this message everytime im kinda new to codding tho so i js want to know why i got this
u do
Bot
capital B
import discord
from discord import Guild, Intents, Invite
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print('Online')
@client.command()
async def dai(ctx):
for invite in discord.Guild.invites:
await invite.delete```
my goal is to delete all the active invite links and this is not working
you need to call invite.delete
how do i do that? can you send an example?
have you used functions
nope
You have..?
i don't have experience with functions that's what i mean
i haven't used functions before
Do some research about methods (functions), class and OOP. @slate swan
If we're explaining something we'd at least expect some knowledge of the Python language.
alright i will but i just need this code immediately, can you maybe solve this one for me?
In this Python Object-Oriented Tutorial, we will begin our series by learning how to create and use classes within Python. Classes allow us to logically group our data and functions in a way that is easy to reuse and also easy to build upon if need be. Let's get started.
Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python...
Amazing tutorial about OOP and classes, it also uses and mentions functions.
#bot-commands
a user input in what way?
like a command to do maths calculations
!command argument1 argument2
``` do you want to get the arguments?
yeah thats what i meant
alr thanks
i get this error with my slash command bot it started like 15 minutes ago what do i do ?
i tried resetting the token
restarting the bot
but nothing works
What command?
your command's signature is not synced with what discord has
Restart your discord client
i require the doingening of this (yeet a command into a subgroup or w/e it's called)
unfortunately
that isn't how you create groups/subcommands https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-subcommand
please don't use ableist language
And we don't help with music bots.
Do we not?
for the record i have papers of me being an autist.. somewhere
and it's not what i'm asking for rn
So you aren't asking help about a Discord bot that can play music?
Correction- could possibly play.
i'll butcher aiode for that later
rn i just want the basics
ok
only seen the group implementation from https://guide.pycord.dev/interactions/application-commands/slash-commands
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
error said: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
so thanks
you're editing a response without actually responding to the interaction
That's right, but I didn't understand that problem really broken head pain xd.
please solution x.x
!d discord.InteractionResponse - you have to respond to the interaction using any of these methods
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 "discord.Interaction.response").
New in version 2.0.
Just defer if you're only trying to edit an already-existing message
ah think there is " im = await interaction.send('Do you want upload image?, or say "N" to skip')"
.send change is send.response? or response.send_message?
bruh.
Btw does anyone know what is meant on the dpy docs by "a traditional avatar" under User.avatar?
"If the user does not have a traditional avatar,
Noneis returned."
Default avatar
okay done think is
response.send_message?
sure
and alrleady change fix, my forget no i dea.
yep thanks and last final problem no solution upload image :/
there check
wut
So default = non-traditional? Thanks
no, default avatars are traditional avatars
Yes
you also have to send a file https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image
ok check thx
How would I do that
The same way you'd normally make a dictionary in Python probably
discord?
π€¨
are you talking about discord.utils?
from discord import utils?
Command 'alertschannel' raised an exception: OperationalError: no such column: alertschannel
@client.tree.command(description='Set Alerts Channel.')
@commands.has_permissions(administrator=True)
async def alertschannel(ctx, channel: discord.TextChannel):
channel = channel.id
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('UPDATE users SET alertschannel= ? WHERE guild = ?', (channel, ctx.guild.id,))
pr = discord.Embed(title="Alerts Channel Set", description=f'Alerts channel has been set to <#{channel}>')
await ctx.response.send_message(embed=pr)
await db.commit()```
im so confused why it isnt working
@client.tree.command(description='Must use this command to set channels.')
@commands.has_permissions(administrator=True)
async def setup(ctx):
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT transactionschannel FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if data:
pass
else:
await ctx.send("Set everything up!")
await cursor.execute('INSERT INTO users (transactionschannel, alertschannel, guild, demandchannel) VALUES (?, ?, ?, ?)', (0, ctx.guild.id, 0,))
await db.commit()```
So how do I edit a role?
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
oh I need to fetch the role itself.
!d discord.app_commands.CommandTree.sync
no?
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:
well, yeah, kinda, you gotta get the role somehow
it'll probably be in your cache
helpem.set_author(name=f"{client.user}", icon_url=ctx.client.user.avatar.url)```
Why doesn't this work
why i see this problem?
ctx.client.user.avatar.url 
python file.py
in this picture its inside a bot folder
in this picture you are not inside a bot folder
so just cd Bot
sorry,
I'm a moron
What is the full path to hikisan
he just needed to cd into the "bot" folder
Yep
you may just want to look into an IDE..
i don't have IDE
I have no idea either
I turned off the light, it doesn't work either
you turned off the light?
Me*
i am mad confused
dudes power went out? lmfao
Hello, I want to print some of my programs print statements inside my discord channel, I also want click able buttons to go to an url.
And i want to add data to my code through a slashcommand. Should I use a webhook, or a full on bot?
bot
well, wait
you want to send a message of your print statements?
well slash commands and a webhook wouldnt work so well, so yes bot
my program prints some events
and I want to see those events in a discord channel
but I also want to append userinput to a file
"hello injections"
Im trying to use py to exe but every time i use it it keeps saying error
@fading marlin
there?
i put the await bot.change_presence in on ready?
yeah hes saying you shouldnt
related to discord bots? o.O
so how i add the status for my bot ?
hes just saying you shouldnt do it in on_ready, you should build something else for the actual config, or literally just make it a command Β―_(γ)_/Β―
whats the error
Pass it into your commands.Bot constructor
... because that's the whole reason it's there for. To pass in an initial activity
like tht?

why do people have to use discord.py and google for discord.js code online
requirements already satisfied
py2exe/pyinstaller is incompatible with discord.py
Talking 2 me
yeah that was my next question, how are you trying to implement dpy to this
yea the py2exe... message was for you
it won't install the dependencies properly
and how i can do that in the commands.bot
!d discord.ext.commands.Bot
i have the commands.bot thing
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
there are a lot of params so open up the docs link and look there
there's no builder.py file in the directory you are in
How the hell do i like open cmd window on the file i want
why its in red if i did the site thing lol
async def x():
await bot.change...
also there's no point of packing a bot into an exe πΏ
ah
directory into a zip?
and eclipse grabber?...
like eclipse token grabber :|
found the point x)
πΏ wow lol

lol dont actually use x, that was just a filler, and you need to indent
indentation man, and ctx is the first argument in all commands
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
there we go, see the status kwarg
its under **options lol, you can read about it in the docs string tho
Bot doesn't explicitly mention it in as a parameter. You gotta check Client for it
so i have to put the ctx right?
So
no help with token stealers basically
yes..
why don't you just use the status arg in Bot
alr,
first you need to async def {something}(ctx):
but as Lee was saying you can put it in constructor and avoid the command altogether
bot = commands.Bot( stuff you have already, status = discord.Status.idle )
omg I had to reread the "stuff you have already" 4 times π
new option, you didnt read the patch notes?
you might also want to lookup into indentation in python
or the basics in general 
π thats my bot's prefix to begin with
guess brain got an update π€·
I don't like this update though
reader function seems to be broken π
welcome to the real world
subclass braincells and make ur own implementation
lmfao
idk how, I can't read!!
thats a lot of sockets
gotta learn it first 
wouldn't say it's real fun, but yeah a nice language to learn. you won't particularly hate it
wasn't there a programming language called lolcode or something like that?
brainf*ck
yeah lolcode exists too
me trying to find a free hosting server that has a database, less rate limits and unlimited total time usage π₯Ή
remove free or get a credit card
Asking for wayyyy too much here
i mean from word of mouth oracle has good free plan if you can verify a card ;p
If that even exists I'd be very surprised
how do i add a time limit to a button
like, they have a certain amount of time till they cant click it anymore
!d discord.ui.View you add the timeout to the view
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
thanks
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
app_commands.Choice(name="General Manager", value="General Manager"),
app_commands.Choice(name="Head Coach", value="Head Coach"),
])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
GMRole = discord.utils.get(i.guild.roles, name="General Manager")
HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
if any(role in FORole for role in i.user.roles):
if any(role.name in nflRoleListNames for role in i.user.roles):
if (position.value == 'General Manager'):
await user.add_roles(GMRole)
if (position.value == 'Head Coach'):
await user.add_roles(HCRole)```
Im trying to make it where, if you have FORole, and and role name in nflRoleListNaames, then It'll give the role depending on which option you pick
its not working, How do I fix it?
discord.app_commands.errors.CommandInvokeError: Command 'promote' raised an exception: TypeError: argument of type 'Role' is not iterable
thats the error
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
You just need to check if FORole in i.user.roles to see if a user has that role
ngl i just chaanged a bunch of things and somehow got it to work
i ended up with this
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
app_commands.Choice(name="General Manager", value="General Manager"),
app_commands.Choice(name="Head Coach", value="Head Coach"),
])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
GMRole = discord.utils.get(i.guild.roles, name="General Manager")
HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
if FORole not in i.user.roles:
await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
if teams not in user.roles:
await i.response.send_message(f"User is not on your team.")
else:
if FORole in i.user.roles:
if any(role.name in nflRoleListNames for role in user.roles):
if (position.value == 'General Manager'):
await user.add_roles(GMRole)
if (position.value == 'Head Coach'):
await user.add_roles(HCRole)```
works perfectly though
but one question how would I make it where, if someone already has GMRole or HCRole then it wont work
if GMRole in i.user.roles or HCRole in i.user.roles:
...
thanks
doesn't work. That is reading, if the person who runs the command has GMRole or HCRole then it wont work. I'm trying to make it where if anyone on the team role has it then it doesnt work
Right, so if the user does have the role, then say something like "You can't use the command" and return
To avoid nesting - you've got plenty going on already π
when i do the command, it checks if I have HC or GM role. If I have the roles then it wont work. If soemone else on the team has it it still goes through
i want it to not go through unless no one has the role on the team
examaple:
if team 1 already has a GM. then you cant give it to someone else. If the team doesn't have a GM then you can.
i feel like this would have been easier from the get go if you started with data instead of using roles to check everything
@tasks.loop(minutes= 30)
async def statscounter(self):
for key in self.serverstats.keys():
guild = self.bot.get_guild(int(key))
try:
server_stats = self.serverstats[str(guild.id)]
except KeyError:
server_stats = {}
category = discord.utils.get(guild.categories, name="STATS")
botcount = 0
membercount = 0
members = guild.members
textchannelscount = len(guild.text_channels)
voicechannelscount = len(guild.voice_channels)
for member in members:
if member.bot == True:
botcount += 1
else:
membercount += 1
users_text = f"Users: {membercount}"
bots_text = f"Bots: {botcount}"
channels_text = f"Text Channels: {textchannelscount}"
channels_voice = f"Voice Channels: {voicechannelscount}"
tier = f"Premium Tier: Level {guild.premium_tier}"
uc = guild.get_channel(server_stats['member_count'])
bc = guild.get_channel(server_stats['bot_count'])
tc = guild.get_channel(server_stats['text_count'])
vc = guild.get_channel(server_stats['voice_count'])
pt = guild.get_channel(server_stats['tier'])```
if uc.name != users_text:
await asyncio.sleep(1)
await uc.edit(name=users_text, category=category)
if bc.name != bots_text:
await asyncio.sleep(1)
await bc.edit(name=bots_text, category=category)
if tc.name != channels_text:
await asyncio.sleep(1)
await tc.edit(name=channels_text, category=category)
if vc.name != channels_voice:
await asyncio.sleep(1)
await vc.edit(name=channels_voice, category=category)
if pt.name != tier:
await asyncio.sleep(1)
await pt.edit(name = tier, category=category)```
why wont this autoupdate every 30 mins?
it would haave to be something like
if teams in user.roles, and if gmrole in teams.
Pretty much, if the user has a team role that the owner does, and if someone on that team has gmrole then it wont work
no clue how to do that though
somebody knows how command βs/text/textβ work
It like replaces previous message
the problem is i dont have one
railway.app only provides 21 days of free service per month ;-;
old computers or a raspi go a long way
zamn
well for one u can only update a channel name 2 times every 10 mins
This is the enemy of DRY π€
how to add buttons?
in d.py?
Offical button example: https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
okay so I dont know how to do this, Im stuck. Anytime someone sends a message in my server which contains the word "VC" in it, then I want the bot to list all the VCs available in the channel and say something like "Perhaps you'd like to join one of these to hang out?" and then when you click on that UI VC, you should be able to join it
@user.event
async def on_message(message):
if "vc" in str(message):
discord.ui.ChannelSelect(channel_types=ChannelType.voice, placeholder="Which VC you wanna join?", min_values=1, max_values=1,disabled=False, row=None)
yeah so Im not doing this right uhhh
can someone help?
do i have to import discord ui?
I dont think thats what channel select is for
I think ChannelSelect is for slash command
Completely new to this, reading documentation and trying to implement stuff
just list all the links and hyperlink their jump url
oh I see, so what do I do then?
just check the example jeez
more clarity maybe?
if vs in message.content:
for channel in message.channel.guild.voice_channels:
...
use list comprehension
is on_message not the right way to do it or
if vs in message.content:
voice_channels = "\n".join([f"{channel.name}" for channel in message.channel.guild.voice_channels])
well is it a command or u just want to check for vc
smth along those lines
its not a command. If someone says "Oh lets join VC" in chat
on phone rn so its hard doing those long lines
well then use on message
I want the bot to be like "Yo these are your options"
So options?
im trying to create a server/website that gets images from my java app in android studio then returns a url of the image (image to url) and it worked for me yesterday but now when i turn on replit it gives me this error: ```python
Traceback (most recent call last):
File "main.py", line 2, in <module>
from werkzeug.utils import secure_filenarme
ImportError: cannot import name 'secure_filenarme' from 'werkzeug.utils' (/home/runner/QrCodeApp-1/venv/lib/python3.8/site-packages/werkzeug/utils.py)
i tried everything but noting works anyone has any idea on how to fix this ?
basically options that the user can then select and then after they select it, they would join whichever one they select
it should be pretty simple, I just dont understand how to do this
Join?
I think I should probably first watch some videos on this or something?
O I got good video
yeah they would join the VC that they select from the options
I wanna be able to do wahtever I want, I just cant go through endless Documentation, this isnt working out
This is the Ultimate Python Guide on Buttons with Discord.py or Pycord. In this video, I talk about how to create buttons in discord.py or pycord and how to respond to button clicks along with everything about Views. After watching this you'll know everything about Buttons and Views in discord.py or pycord.
This video might also apply to other...
Bots can't connect users to voice chats
Well you can't force user to join vc
If you mean that
okay then like a link to the VC I guess, just invite them to whichever one they select
This video covers everything about interactions for most discord py libs
Like pycord nextcord ect
?
Did you put __init__.py in folder?
wdym ?
i dont have a __init.py__ file
In order to import files from folders you must make that file
i didnt import from a folder
or a file
from werkzeug.utils import secure_filenarme
So it isn't local file
i have an error here
It's a module??
Yea
It might be due to version of the module
So in the terminal of repl pip install -U Werkzeug==0.16.0
tried to change it to other version pepole said it worked for them on
didnt work
but il try pip install -U Werkzeug==0.16.0
Ok good luck
nope not working
Weird
I'm not familiar with the module sorry
all good
Replit uses poetry, why use pip there
Sarth once said
but i am doing it once every 30 mins
eh?
It doesn't differ much like install is just poetry add
But it provides better dependencies management, it allows grouping them, and if you remove main dependency it will remove all the unneeded subdependencies
Same code with different objects somewhere can be refactored, in your case you could use for loop
for role in guild.roles[1:4]:
overwrites[role] = discord.PermissionOverwrite(view_channel=True)
await guild.create_text_channel(f"Ticket-{payload.member.display_name}", overwrites=overwrites)```
How can i disable multiple channels create
Wdym
You could do if the channel is in ctx.guild.channels
its simple ticket system but with event on_raw_reaction_add but i dont know how can i block multiple tickets opening
Database would be recommended but you could make channel name have user id in it and loop through all channels in guild and check if channel user id are there and not create channel
Idk but its only for my server thats the reason why i didnt need db
Can u explain me if channel user id
You still need db
And store user id into database once ticket is open and remove when closed
Would be more efficient and channel then could be any name but with user id method you would need to put user id in channel name which looks tacky and unprofessional
i m not able to use jishaku this error occur's
main.py:17: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension("jishaku")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
@slate swan
Hmmm
can you help me ?
await Botbase.loadExtension?
its a breaking change from d.py 2.0, load_extension needs to be awaited
https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
now how can i fix it
"needs to be awaited"
they told u to await it...
they even sent you the docs 
@rare echo@slate swan@quick gust
very cool
so u want us to spoonfeed you?
u have to await it is probably the simplest thing we can say
u can google "how to await a function"
have a look at the docs, try to read and understand using the explanations and examples
how do I get the number of people who pressed a button in a message?
discord.py is not a beginner friendly Library, and awaiting is a very basic task you should know if you're making a bot
you'll have to keep a track of each button click indivisually in a variable
i tried that
what was wrong with it?
im using pycord and i made a nonlocal variable but it is saying SyntaxError: no binding for nonlocal 'countx' found
do you have the code?
yes
class joingame(discord.ui.View): countx = 0 @discord.ui.button(label=f"Join game", style=discord.ButtonStyle.primary) async def button_callback(self, button, interaction): nonlocal countx countx += 1 await interaction.response.send_message(f"{interaction.user} has joined this game!")
remove nonlocal for it, and either setup a custom id to separate guilds or even easier, use a db
self.countx += 1
why would you use nonlocal here, its a classvar
does he really need self if its just a global var increment?
nvm didnt realize it was in the class 
thx
how to get this badge?
Be a developer
How to become
add a slash command to ur bot and apply for the badge
I know how to add timeout like a certain time they have to click it, but how do I make it where once you click a button once you canβt click it again
So I have a system with commands etc but I am wondering how I can make a command able to be used only 1 time everyday by users ?
use a cooldown
add a cooldown to the cmd
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
But like this each user can use it 1 time per day or the whole command can be used 1 time by anyone?
^ or can you not do that
new to using buttons
My command isn't using buttons though
Iβm asking about my command
Code
you'll have to use a database (if the view containing the buttons is persistent) or a cache
Learn to code
Coding is great
sometimes
All my homies love coding
Always
Fr
Come on we are literally wizards who control the magic stones
We speak the language of the stones
We write words on a screen and get 100-500k salaries
This is what I have
button = Button(label= "Confirm", style=discord.ButtonStyle.green)
force = Button(label="Force Sign", style=discord.ButtonStyle.red)
view = View(timeout = 120)
view.add_item(button)
view.add_item(force)```
you're making it sound easy lol
Put buttons into a class
do their views have to be persistent? looking at the initial message i was thinking shawn's asking how to disable the buttons after one of them is clicked
What's the difference between
on_app_command_error1
And
on_app_command_error2
none of them exist in the library
Which one should I use for cooldown
!d discord.app_commands.CommandTree.on_error
await on_error(interaction, error, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command "discord.Interaction.command") should be used.
No I meant that if they are persistent then a database would be required instead of a cache
You can edit the message and disable it
but there's no role of persistence in that lol
ya
thatβs what I meant
When the buttons are clicked they expire
in the button callback need to loop through the rest of the buttons attached to your view, disable them, and then edit the message with the newly disabled buttons
!d discord.ui.Button.disabled you need to set the disable property to True and edit the view
property disabled```
Whether the button is disabled or not.
thanks
why do i get this error?
you probably didnβt install discord.py
πΏ
How I can get the badge for my bot
add a slash command to it
Can you give me
no i cannot give you slash commands
you will have to make them yourself
you can look at examples online
and UNDERSTAND it
LOL
what
@delicate pilot
i suggest understanding python first
you will keep encountering hurdles if you straight away jump to dpy
How do you edit a view? I got the disable part down but I donβt know how to edit a view
you edit the message and pass the new view, thats all
when you edit the component of the view, it gets updated as well
No point getting badge if you're not actually a dev
Defeats the purpose so you must learn on you're own
Facts
badges are overrated, open source your project if you really wanna flex lol π€Ί
Do you have any courses
!resources here's decent resources to learn python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
The one good thing that came out of the badges
New potential developers who want to learn
and some people actually trying slash commands for once
π the badge design could have been better tho, a bit of modifications in <>
No people are just using GitHub code I saw some person named ntts promote some shΓ―tty GitHub code and taking lazy way
Right but there are also a few people who are genuinely interested
Then asking them how do you iterate through list in python and they can't answer
Because there's not actually devs
You probably need to update yr discord.py or smth
Wait
the import is from discord.ext import commands and then use commands.Bot
help
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="!")
bot.run(os.getenv("TOKEN"))
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
thx
no sorry i js saw
i dont use cogs
wym sorry im kinda new to this lol like i need to retype the whole thing?
i dont think so
I googled it it is
@kick.error
async def kick_error(error, ctx):
if isinstance(error, MissingPermissions):
await ctx.channel.send("Looks like you don't have the perm.")
now its this lol
Try ctx.author instead of ctx.member
can any1 help me out
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide 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 "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
this is probably what you're after
to check the bot has permissions use bot_has_permissions instead
@
It should be commands.has_permissions
like that?
Lowercase c
and has_permissions is an attribute of commands
Dot notation
It should be exactly as Matser typed it, and remember you need from discord.ext import commands if you haven't already.
Dog notation lol
Dog notation kek
πΆ
Everything working now?
i have this big message appearing lol
Show ban command
make sure its discord.Member in your parameter typehint, with capital M
CamelCase! ^
also your string has to be an f string
naw thats PascalCase
Member with capital M
is that possible to add the user mention?
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Notice the f before the ""
Python Enhancement Proposals (PEPs)
funnily enough there's one source that actually points out how dumbfoundingly confusing the definition is https://www.theserverside.com/answer/Pascal-case-vs-camel-case-Whats-the-difference
Camel case and Pascal case are similar. Both demand variables made from compound words and have the first letter of each appended word written with an uppercase letter. The difference is that Pascal case requires the first letter to be uppercase as well, while camel case does not.
one last question is that possible to remove the 'member' in front of the tag
Remove it from the string
alrr
i havent seen a string representation like that before ah they manually wrote it
There's 2 kinds of camelcase, 2 bump and 1 bump, so you can use CamelCase and PascalCase as synonyms really
hi
like that @sick birch
LGTM
do you guys have any project recommendations for beginners?
!projects
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
if i want the bot to tag the user when they join do i need to put the member.mention in front?
?
anything wrong w that? cuz my friend dont have perm to ban and she banned sm1?
show us the code of your kick command
@quick gust
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide 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 "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
noo it's a decorator
ooo
@has_permissions(<perm>)
like that sorry im kinda new to this
no
@bot.command() is a decorator
it "decorates" the function
u put the has permissions decorator below or above that
without any indents
oh
also add a =True after administrator
yeah
considering you want the permission to be admin, there's more specific ones like ban_members I think
yeah and kick_members too
ctx, error, not the other way around
also context objects have a send shortcut coroutine
wym/
ctx.send(...) instead of ctx.channel.send(...)
@ban.error
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
how lol
why it do that?
thats what you get for using replit π€‘
your indentation is wrong
hi
i tried to use argparse to do this:
but it seems to be blocking and slow
any better way to do that?
discord.py has those
!d discord.ext.commands.FlagConverter
class discord.ext.commands.FlagConverter```
A converter that allows for a user-friendly flag syntax.
The flags are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations similar to the [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses "(in Python v3.11)") Python module. For more information on how this converter works, check the appropriate [documentation](https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#ext-commands-flag-converter).
iter(x) Returns an iterator of `(flag_name, flag_value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
i dont think it works the same way i want
oh lol
i need to have flags that start with -- to make it more similar to a cli
there is an option to do that, lemme find the examplee
# --hello world syntax
class PosixLikeFlags(commands.FlagConverter, delimiter=' ', prefix='--'):
hello: str
nvm
can i just copy everything and switch to virtual studio code?
thank you
π
can't i have 2 delimiters?
wdym?
" " and "="
k then " " makes more sense
yea just make to install your dependencies
How to set
@discord.ext.commands.cooldown
Cooldown by user not for whole guild etc
its for a user by default
No it's for everyone for me
Lemme show you how I set it
@discord.ext.commands.cooldown(1, 600, type=discord.ext.commands.BucketType.default)
How do I turn it by the user?
@slate swan
BucketType.user
Command 'foapp' raised an exception: ValueError: could not find open space for item
what does that mean
you need to install it
install discord.py
lmao well thats not tje issue here
LOL
the import would be valid if dpy was installed
i never used this before
told ya earlier, install dependencies before running file
pip install discord.py
i got it
The import is technically valid
js to make sure the pip install discord.py its in cmd prompt right
yet useless
or excessive, whatever you wanna call it
Is it?
given the fact that they are importing discord/commands in the code π€·ββοΈ it is
Wasn't referring to that but alright
didnt get you then, sorry
wasnt this thing on github blue instead of green just a few hrs ago
it's always been green π€
oh, neat
!pastebin your entire code, please
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
For some reason, the .cards command isn't doing ANYTHING.
Its not printing anything out for an exception, its not sending anything to the chat, even when i add debugging prints they don't even run even though i put them on the FIRST line.
But the other commands work?
yep.
any1 know a site for host my bot?
I'm not seeing the print statement reflected in the pastebin
I removed them, but even with putting print(number) after every line. It didn't print anything to the console.
Can you show us the code with the print statements?
Sure!
Here you go: https://paste.pythondiscord.com/qetazipofo
i can pay idc
I have figured it out, it had to do with the not having a = None and something with the len() command
AWS
whats the website?
alrr
I use AWS for hosting my websites and it's great
perfectt
How can I add an embed like this because an embed requires you to have a name (where the text is always bold, which I don't want), but if i use a whitespace character to bypass name, then there is just a empty line space, how can i make it look like the pic above without any additional line spaces
No, embeds aren't required to have a title
they just have to have some sort of content
it seems your image link is broken
get a working image link? your command is written just fine, you just need an image url that actually gives you a picture
is there possible to add a autotrigger any1 have the link or know how
could you give a bit more context? autotrigger for what? when should it trigger?
like when sm1 say goodnight the bot answer
!d discord.on_message this event gets dispatched every time someone sends a message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
ty
Command 'pickups' raised an exception: ValueError: Connection closed
what does that mean
you'll have to send more than the error
@client.tree.command(description='Start a pickup')
@commands.cooldown(1, 600, commands.BucketType.user)
async def pickups(ctx, opponent: discord.Member, link: str):
pickupseem = discord.Embed(title="Test")
pickupseem.set_thumbnail(url=f"{ctx.guild.icon}")
pickupseem.set_author(name=f"{client.user}", icon_url=client.user.avatar)
if 'https://www.roblox.com/games/8204899140?privateServerLinkCode=' not in link:
await ctx.response.send_message("Invalid Link", ephemeral=True)
else:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT setpickupschannel FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if not data:
pass
else:
channel = client.get_channel(int(data[0]))
async with aiosqlite.connect("main.db2") as db2:
async with db2.cursor() as cursor:
await cursor.execute('SELECT setcaptainrole FROM users WHERE guild = ?', (ctx.guild.id,))
data = await cursor.fetchone()
if not data:
pass
else:
role = ctx.guild.get_role(int(data[0]))
if 'https://www.roblox.com/games/8204899140?privateServerLinkCode=' in link:
if role in ctx.user.roles:
await ctx.response.send_message("Succesfully Sent Pickup.", ephemeral=True)
await channel.send(embed=pickupseem)
await channel.send(f"@here")```
why are you opening and closing 2 connections in the same command?
also, consider doing ```py
if data:
channel = client.get_channel(...)
and remove the `else`. It makes your code more readable
anyway, for the actual error, you're calling cursor.fetchone outside of the context manager
whaat does thaat mean
@sick birch wich one i need to select
Compute > EC2
what's wrong here?
- calling
aiosqlite.connect(...)creates a new connection. You're doing that twice in your command... why? - your if statements aren't really readable
if not data:
pass
else:
...
is exactly the same as doing
if data:
...
consider doing the latter instead
withstatements are also called context managers
# outside the context manager
with open(...) as fp:
... # inside the context manager
# outside the context manager
when you exit connect's context manager, you're closing the connection between your database. Once your connection is closed, you cannot interact with the database anymore. cursor.fetchone requires you to have an open connection, but you're calling it outside the context manager
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print("Bot started")
await Bot.change_presence(status=discord.Status.idle, activity=discord.game(""))
bot.run('TOKEN')
what he doesn't like about bot.run('TOKEN')
that you're not passing an actual token
don't change presences in on_ready either
commands.Bot has an activity and status kwarg
ok
i can host ur bot in my vps
24/7
also https://ask-your-mom.big-pp.club/π²π»π₯’π₯Ί why my replit gives this error
dm me
because replit uses shared IPs, and you're getting ratelimited because of it
not a good idea lol
why
would you give me the token of your bot? probably not. Same thing applies
I would not be placing some random person's supposed host over an industry standard like AWS
oh okok
im posting this as a new method of showing people a locally hosted bot
is there way to find a role with only the first half of the role name provided?
ex: find the role named "pic perms" with only the "pic" parameter
You could iterate over the guilds roles and check if the role name starts with the provided name
Sure:
filtered_roles = filter(lambda x: x.startswith(...), roles)
Where roles is a Sequence[discord.Role]
how to get this badge?
I made a bot that has a command through a slash
Claim it from the dashboard
If it's not there it can take a while
If it's still not there then discord probably put more restrictions on it
why when i put these commands other commands dont work
you need uhh, bot.process_commands i think its called
yes , await bot.process_commands(message)
Use @bot.listen() instead of @bot.event
It lets you:
- Have more than one
on_message(events don't let you do this) - Not need to use
bot.process_commands
I'm still trying to fix this. This is my current code. It's still not working.
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
app_commands.Choice(name="General Manager", value="General Manager"),
app_commands.Choice(name="Head Coach", value="Head Coach"),
])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
GMRole = discord.utils.get(i.guild.roles, name="General Manager")
HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
if FORole not in i.user.roles:
await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
return
if teams not in user.roles:
await i.response.send_message(f"User is not on your team.")
return
if GMRole in i.user.roles or HCRole in i.user.roles:
await i.response.send_message("Someone is already coach")
return
else:
if FORole in i.user.roles:
if any(role.name in nflRoleListNames for role in user.roles):
if (position.value == 'General Manager'):
await user.add_roles(GMRole)
await i.response.send_message(f"Promoted user to General Manager")
if (position.value == 'Head Coach'):
await user.add_roles(HCRole)
await i.response.send_message("Promoted user to Head Coach")```
If the team alreaady has GMRole or HCRole, then you cant run the command thats whats supposed to happen but it doesnt work
ty robinn
one last question if i want to add a channel in my welcome message its like that?
i added the id of the channel w #
oh nvm, that should work to just mention it
yea
<#ID>
exactly what i did
^ Does anyone know how to make this work?
I'm trying to make it where, if someone in teams has GMRole or HCRole then do something.
idk how to makae it where if SOMEONE in teams has
i only know if teams in user
If I'm understanding your question correctly, you will need to get all members of team role and then check if any member has GMRole or HCRole
exactly
exactly what im trying to do. Idk how to though
0 clue
if i want to add a emoji to a message how i can do that?
<:emojiname:emojiID>
a custom emoji ^
alr
@fair shuttle put the emoji and put \ before it
then send
it gives u the whole thing
like that
yea

is it from the same server? Might be why
the bot has to be in the server the emoji is in i think
oh
yeaa so just upload the emoji in ur seerver and try
yeah
a bit off topic but what is going on
my bot is in 100 servers and i verified myself now what
is it possible to add SelectOptions to a select menu in pycord using for loop?
yes it is
how?
^ still trying to figure out if any 1 knows
You can get the members of a role with role.members. Then you can check GMRole in member.roles or HMRole in member.roles
par = {
"option_one" :
{"label": "Red",
"value" : "red"},
"option_two":
{"label": "Blue",
"value": "blue"}}
for param in par:
self.add_item(SelectOption(label = param["label"], value = param["value"])) #whatever the method is to add select options if not add_item
you can use any iterable you desire
so like if any(role.members in GMRole for role in members.roles): or something
`class Shoot(discord.ui.View):
players = joingame.players
@discord.ui.select(
placeholder="Choose a person to shoot!",
min_values=1,
max_values=1,
options=[]
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"You have shooted them")`
my current code is like this. it will give an error when i try to put the for loop anywhere in it
what error
sup
switch select, interation by interaction, select
class Shoot(discord.ui.View):
players = joingame.players
@discord.ui.select(
placeholder="Choose a person to shoot!",
min_values=1,
max_values=1,
options=[]
for player in players:
self.add_item(SelectOption(label = player, value = "shoot this player."))
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"You have shooted them")```
this is code:
it will give `Syntax Error: invalid syntax`
there is role.members
Try
if GMRole in [member_role for team_member in team.members for member_role in team_member.roles]:
bro
use the __init__ method
def __init__(self) -> None:
for ...
ok
broo this took forever
thanks bro it worked
Haha you gotta checks docs know some python tricks to pull these things off
Np
expected type item but got SelectOption instead..
yo one question, gonna be a little confusing.
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
GMRole = discord.utils.get(i.guild.roles, name="General Manager")
HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
if FORole not in i.user.roles:
await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
return
if teams not in user.roles:
await i.response.send_message(f"User is not on your team.")
return
if GMRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
await i.response.send_message("Someone is already General Manager")
return
if HCRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
await i.response.send_message("Someone is already Head Coach")
return
else:
if FORole in i.user.roles:
if any(role.name in nflRoleListNames for role in user.roles):
if (position.value == 'General Manager'):
await user.add_roles(GMRole)
await i.response.send_message(f"Promoted user to General Manager")
if (position.value == 'Head Coach'):
await user.add_roles(HCRole)
await i.response.send_message("Promoted user to Head Coach")```
There are 2 coach roles. It's supposed to be, all teams can have 1 GMRole and 1 HCRole. When I promote someon to GMRole, I cant to HCRole it says someone is already general manager, but it should only say that if i try to promote someone to GMRole when there alreaady is one. How do i fix this?
i explained it awfully but
hopefully you understand if u dont ill try to explain better
Better explanation.
Every team has a maximum of 1 GMRole and 1 HCRole. If the team alreaady has a GMRole and you try to run the command. It'll say Someone is already general manager. Which is good. But when I try to promote someone to HCRole, It'll say the same thing. (someone is already general manager) It shouldn't do that because HCRole has its own if statement.
then define somehow the user who can do the promotes!. If I understand correctly.\
@client.tree.command(name='promote', description='Promote a player.')
@app_commands.choices(position=[
app_commands.Choice(name="General Manager", value="General Manager"),
app_commands.Choice(name="Head Coach", value="Head Coach"),
])
async def promote(i: discord.Interaction, user:discord.Member, position: app_commands.Choice[str]):
GMRole = discord.utils.get(i.guild.roles, name="General Manager")
HCRole = discord.utils.get(i.guild.roles, name="Head Coach")
FORole = discord.utils.get(i.guild.roles, name="Franchise Owner")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, i.user.roles)
teams2 = discord.utils.find(lambda r: r.name in nflRoleListNames, user.roles)
if FORole not in i.user.roles:
await i.response.send_message("You are not a Franchise Owner.", ephemeral=True)
return
if teams not in user.roles:
await i.response.send_message(f"User is not on your team.")
return
else:
if FORole in i.user.roles:
if any(role.name in nflRoleListNames for role in user.roles):
if GMRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
await i.response.send_message(f"Someone is already General Manager", ephemeral=True)
return
if (position.value == 'General Manager'):
await user.add_roles(GMRole)
await i.response.send_message(f"Promoted user to General Manager")
return
else:
if HCRole in [member_role for team_member in teams2.members for member_role in team_member.roles]:
await i.response.send_message(f"Someone is already Head Coach", ephemeral=True)
return
else:
if (position.value == 'Head Coach'):
await user.add_roles(HCRole)
await i.response.send_message("Promoted user to Head Coach")
return```
everytime I add HCRole, it says someeonmee is aalready geeneral manager
idk why though, i returneed it, I did else:
idk why when i do HCRole it gives me the GMRole message
anyone know where to find a list where stuff like on_member_join and on_member_remove would be
The indentation is really fucked on discord mobile. Would it be possible for you to send a screenshot of the code editor
i fixed it alreaady its fine
The event reference section in the docs
Oh cool
what does ProgrammingError: Cannot operate on a closed cursor. mean
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT settransactionschannel FROM users WHERE guild = ?', (i.guild.id,))
data = await cursor.fetchone()
if not data:
pass
else:
channel = client.get_channel(int(data[0]))
await channel.send_message(embed=promoteem)
return```
You're trying to use cursor variable outside the context manager it was created
Just move it 1 indent up
how do Cogs work? If I want to use a similar way to define methods in different folders and combine them into one class
do they just inherit each class until everything is inherited
Are you asking how to use cogs? Or how does the internals work
I think he means internals
Cogs act like a module in a way. The Cog class that you inherit uses a meta-class to scan all methods before construction to "bind" commands and listeners to the Cog class. Afterwards using load_extension does an importlib lookup where it looks for the module using the path, E.g foo.bar then looks for a TOP-level method setup that just binds the Bot instance to the cog via injecting commands & listeners that were binded to the Cog earlier
!e ```py
from typing import Any, Callable, Self
class FooMeta(type):
commands: dict[str, Callable]
def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> Self:
commands: dict[str, Callable] = {}
for key, value in namespace.items():
if callable(value):
commands[key] = value
namespace["__commands__"] = commands
return super().__new__(cls, name, bases, namespace)
class Foo(metaclass=FooMeta):
commands: dict[str, Callable]
def __init__(self) -> None:
self.commands = self.__class__.__commands__
class Cog(Foo):
def foo(self) -> None:
print("bar")
cog = Cog()
print(cog.commands)
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'foo': <function Cog.foo at 0x7ff1105cc4a0>}
im following a tutorial to make a discord bot and im getting the error "client has no attribute command" for @opaque fiber
Don't follow tutorials
Most of them won't teach you anything
And only discord.ext.commands.Bot has command decorator
!d discord.ext.commands.Bot.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
@bot.command()
async def lock(ctx, channel: discord.TextChannel = None):
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.send_messages = False
await ctx.channel.set_permissions(ctx.guild.default_role,
overwrite=overwrite)
await ctx.send('Channel locked.')
``` how can i make it lock a particular channel for a particular role
Pass the role object into the set_permissions method
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
thanks the api link helped more than the tutorial
how so ? can i have a syntax pls
cause i tried and it didnt work
you ask for a channel arg in the command and yet you're editing ctx.channel, why?
Exact same but with other role that's not ctx.guild.default_role
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
@client.command()
async def lock(ctx, channel : discord.TextChannel=None):
overwrite = ctx.channel.overwrites_for(ctx.guild.get_role(934391119041687593))
overwrite.send_messages = False
channel = client.get_channel(936641493534404638)
await ctx.channel.set_permissions( overwrite=overwrite)
print("heyo")
await ctx.send('Channel locked.')
``` like this ?
Edit the message with the edited view
edit_message(content="your stuff", view=self)
edit_message has kwargs only
use a proper IDE and type checker to avoid mistakes like this
Hi o7 new here so sorry for the absolute beginner questions, I will have a few over the next few weeks probably π
Is there a website which will help create a slash command modal form in python?
I used an online site to create a bot previously and it was in java but I want to host my own bot and write it in python instead and I have search several modal results but cant find anything and I'm struggling to understand it
I need a modal form to popup when a user types /rally
!d discord.ui.Modal
