#discord-bots
1 messages · Page 155 of 1
Not in your code - run the command in your terminal
int is an integer, it'll accept channel IDs
How would I go about doing that?
integer..
Press the 3 dots next to "Problems", select "Terminal", and type that in
but you may have to take it as a str and then convert it because of discords input, i had to anyway
I did that and it looks like it ran and installed successfully but it still says it can't be resolved.
Usually you'll have to restart your VSC for changes to take effect
Yeah it takes a hot second to resolve
I just needed to remove .py. Tyvm for your help it is greatly appreciated ❤️
anyone here got a big brain idea of how to send a modal if a response has been deferred?
i believe that you can't send a followup modal, it needs to be the initial response, the API doesn't provide it
does anyone know how to make these slash commands instead of prefix commands using nextcord? I was watching a tutorial but it doesnt show how to make them slash commands
!pypi discord thats a different library
A mirror package for discord.py. Please install that instead.
can i do a for loop inside a for loop? trying to get recent channel history for every channel in a guild and its giving me a syntax error because i tried doing for every channel do this for every message
Of course, you can
messages = [msg async for msg in channel.history(after=seven_days_ago)]
for message in messages:```
its giving me a syntax error on that second for
The closing ] is missing
its there in the code, i had to retype because its a remote vm and i cant copy paste
disregard, thanks 
🐈
trying to filter out roles for members im looking at in channel history, keep getting the error that User object has no attribute roles. how would i filter out the people that have left in my role sorting since they dont have a member object just user
nvm i used mutual servers
im using nextcord
like changibg it same as dpy to interaction and bot.slash_command
if mutedRole in user.roles:
print(user.roles)
await user.remove_roles(mutedRole)
embed = discord.Embed(description=f"**Unmuted {user.mention}.\nMute time is now over.**",colour=discord.Colour.green())
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853533870891859968.png?size=96")
await mutechan.send(embed=embed)
else:
pass
self.ezmute[str(guild.id)].pop(userid)
self.saveFile(self.ezmute, "moderation.json")
return```
whats wrong in this?
any error?
Nice variable names
nope
pass
self.ezmute[str(guild.id)].pop(userid)
self.saveFile(self.ezmute, "moderation.json")
return
its a task.event
well i tried printing every line of the code
the codee i shared the first line , its not prnting after it
What is in the userid var
@tasks.loop(seconds=60)
async def unmutetime(self):
unmutetime = mutemsg.created_at + datetime.timedelta(seconds=time)
x = discord.utils.utcnow()
if x >= unmutetime:
print("this works")
mutedRole = discord.utils.get(guild.roles, name="Muted")
print ("mutedroles") this also works
if mutedRole in user.roles:
print(user.roles) this doesnt print
print("role+")
await user.remove_roles(mutedRole)
print("role removed")
embed = discord.Embed(description=f"**Unmuted {user.mention}.\nMute time is now over.**",colour=discord.Colour.green())
print("before thumb")
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/853533870891859968.png?size=96")
print("after thumb")
await mutechan.send(embed=embed)
else:
print("passed")
pass
self.ezmute[str(guild.id)].pop(userid)
print("popped")
self.saveFile(self.ezmute, "moderation.json")
return
except KeyError:
return```
the user id
Eh
for key in self.ezmute.keys():
guild = self.bot.get_guild(int(key))
try:
for key in self.ezmute[str(guild.id)].keys():
userid = key
msgid = self.ezmute[str(guild.id)][key]["msgid"]
chid = self.ezmute[str(guild.id)][key]["chanid"]
time = self.ezmute[str(guild.id)][key]["timeleft"]
mutechan = self.bot.get_channel(chid)
user = guild.get_member(userid) or guild.fetch_member(userid)
mutemsg = await mutechan.fetch_message(msgid)```
fetching it from a json file
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.
why u have for key 2 times
tried printing key?
you're returning on any KeyError within the code, totally not good way of debugging
- json as a database is wack
ik worse than json 
prints the user id
xd
okay i guesss its not able to find the user
<coroutine object Guild.fetch_member at 0x00000207191F9940>
it fetched the member object
[2022-12-14 13:06:28] [INFO ] discord.client: logging in using static token
[2022-12-14 13:06:29] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 3beb7e716f3e54b6cc7ae2fa050a5ef1).
[2022-12-14 13:06:33] [WARNING ] discord.http: We are being rate limited. PATCH https://discord.com/api/v10/users/@me responded with 429. Retrying in 993.40 seconds.
can someone help me with this?
You're doing something too fast
either u sending messages too fast or either u r restarting bot repeatedly or either u deleting something fast
how to do it?
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
@fallow tree
ye
check those libraries bottom of the embed
checking
Hello!
I am trying to make a thing where it asks for a value to then it edits a value
Code:
from CONFIG import VALUE
api = input("New value: ")
How would I make it so it edits the value in CONFIG.py? (yes this is for discord bots, just don't know how)
You mean edit the file or just the value at runtime
I want it to update the VALUE in config, with the value from the input.
And is it have to update the file or just the value at runtime
It just updates that specific value.
Well, that's what I want it to do.
Then you can just assign the new value to it
But how would I edit it permanently?
It's in a different file.
Create a JSON or YAML file to be the config file then 🤷
Much easier to edit and save
There is no way to do it with another python file?
its only showing this
If you'd create consts I guess.
But saving them is only temporary unless you want cursed python code.
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.mute' raised an error: TypeError: unknown parameter given: choices
@commands.hybrid_command(
name="mute",
description="Мутит выбраного участника",
with_app_command=True
)
@app_commands.choices(choices=[
app_commands.Choice(name="5min", value=5), #value = int(minutes of mute)
app_commands.Choice(name="30min", value=30),
app_commands.Choice(name="60min", value=60), #1h
app_commands.Choice(name="120min", value=120), #2h
app_commands.Choice(name="1440min", value=1440), #1day
])
@app_commands.choices(choices=[
app_commands.Choice(name="voice_mute", value=1),
app_commands.Choice(name="text_mute", value=2)
])
async def mute(
self,
interaction: discord.Interaction,
member: discord.Member,
amount: app_commands.Choice[int],
type: app_commands.Choice[int]
):
you're using the choices decorator wrong
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.choices
I'm using a subcommand, and is it possible to set a custom signature to it that will be displayed using command.signature?
Hello, how to make a lot of arguments in command?
*args iirc
thanks
Wdym a lot? Elaborate
import discord
from discord import utils
from discord.ext import commands
from discord.ext.commands import Bot
from time import sleep
bot = Bot(command_prefix=".")
bot.remove_command('help')
@bot.event
async def on_ready():
print(f'{bot.user} is connected!')
@bot.event
async def on_message(message):
await bot.process_commands(message)
@bot.command()
async def hello(ctx):
await ctx.send(f'Привет, {ctx.author.mention}')
@bot.command()
@commands.has_permissions(administrator = True)
async def mute(ctx, member, *, time):
print(member)
print(time)
bot.run("***")
whats wrong
If you don't know what's wrong how can anyone else do
Is there a reason for my discord bot to refuse joining my server 😭
Bro just doesn’t want to join
check if its banned lol
!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.
You should be getting an error in your terminal
If not, your dpy is outdated
is hikari good for discord bot or should i learn smth else
I recommend discord.py, it supports everything you need
no one uses hikari
i heard there wont be any updates on it smth like that
That's nearly 2 year old news
that's old news, it has been recontinued
upto you, discord.py is used more but hikari provides you a cleaner API
Hmm
i personally have 2 projects running on hikari rn lol
I am lit confused
how experienced are you with python?
we'll I'll suggest dpy then, hikari is a bit harder for beginners
you can actually try using both of them for sometime and decide
discord.py
or hikari with lightbulb
both are easy for beginners
i’ve found that you’ll find more support with dpy
in this channel yes
yeah their support server seems very
aggressive to new users except aggressive isn’t the right word
in support server of respective libs, hikari is much better than discord.py's
^
Okay sir🫡
There are 2 right
Light blub
lightbulb is an extension for making commands with hikari
How is another one
The another extension for hikari
There are 2 right?
tanjun?
Yeah
dpy is always the easiest
Hmm
lightbulb is old and easy
tanjun is way too advanced
crescent is easiest thing to exist
crescent only supports app commands tho
extension?
Yeah
!pip hikari-lightbulb
Ig
i sea
!pip hikari-tanjun
I am going with hikari
have fun :D
Which one should I go with tanjun or lightbulb
I'm getting this error using slash commands with autocomplete (nextcord), but theres no useful traceback. How can I fix it?
feel free to ping me if you face any issues related to it, or just use their help server if you ain't able to find quick help here (.gg/hikari is the vanity)
why are there ( lmao its weird
lightbulb is good for starters
🫡🫡
What is the difference
tanjun makes you create a seperate handler client for commands and makes you do things manually, with a high reliability on dependency injection
lightbulb is simple, subclasses the main bot class for command handler and has easy interface
🫡
My bot is verified and I don't really want to request message content. I know that you can get message content whenever someone mentions the bot. Does it also work when someone replies the bot with @ ON
replying while @ ON is kind of a mention
@tough lance yep
Hi new person :3
i am not new
I just checked, there isn't any option to turn ping on or off while replying to a bot.
the acc is just new xd
I know, why are you tough? 
i was really?
shit ig i forgot to use emojis 🙂
huh?
!topic
!e asdd
there definitely is
also it works too
it isn't its just highlighted
wait imma check real quick
ok confirmed, there is no @ option while replying to a "app command"
ephemeral responses can't be replied to.
int's not ephemeral btw xd
It isn't ephemeral its just highlighted
i also too thought it's ephemeral
There isn't any dismiss message option
same applies for any kind of response
!topic
...
Its working in this server but not in the testing server
oh, now everything is clear
with slashcommands:
How actually do I get the content when someone replies. I'm using disnake.
I mean how to catch it
check docs
!d discord.Message.reference will not be None
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
nice exists
oh thanks now I can try it.
makes sense 💀
who knows if they changed that to lil bit xd
Just checked, it works
guys I need help asap
I have a discord predictor bot for blox flip and rblx wild but I want to make it in an app like a app where u can use the predictor.
huh
so go make it...
Hello guys
Is it possible to implement a function to delete it, if the title of the embed message written in the channel is the same as the title in the newly sent embed message ??
anyone got open source discord bot project. I just need example to better understand discord.py
!contribute
Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!
Projects to Contribute to
• Sir Lancebot - our fun, beginner-friendly bot
• Python - our utility & moderation bot
• Site - resources, guides, and more
Where to start
- Read our contribution guide
- Chat with us in #dev-contrib if you're ready to jump in or have any questions
- Open an issue or ask to be assigned to an issue to work on
thank you
do I need to know about OOP before starting discord py ?
It certainly helps, as well as knowing the basics of async
its recommended to know the basics
atleast things like the difference between a class instance and a type
I see in the code source thing like that :
isn't it OOP ?
indeed it is, everything in python is Object oriented
I mean that's some advanced thing
what's the discord.py attribute for a user's avatar?
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
What are you testing?
Nothing
No documentation found for the requested symbol.
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
You figure out?
Hey guys I had a question regarding discord.py button
how can i make a command repeat itself by pressing the button
i got all the stuff sorted but the button is a pain in the 😐
i want to send a new meme when the button is pressed
wth interaction=discord.Interaction
it means what it says 
just save the message and edit the embed containing the meme in the button callback
its in the official repo so ye
u have no idea what it means
we later use it to callback
what u need is a typehint interaction: discord.Interaction
yo i need help rq
How can i edit a slash message?
i try to run the code but it just says no moduled named discord
even tho i have already installed discord and stuff
I trying to use await message.edit()
But doesn't works
which lib?
My code:
@app_commands.command(name='ping', description="Shows the bot's latency in ms.")
async def ping(self, interaction: discord.Interaction):
""" use /ping for ping command"""
latency = round(self.bot.latency * 1000)
message = await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
await asyncio.sleep(0.3)
await message.edit(content=f'\n{latency}ms ') # Here doens't works
make sure you have restarted your ide and checked your python version in which you installed the library
only
i have 3.10.8
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Oh thank you
You helped a lot
chek that
hm
is the python version in vscode the same as in which you installed dpy?
yeah ofc
Did anyone of you played around with ChatGPT? Like integrated it into a Discord Bot?
i fixed it ty for the help anyway
cool
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
grab a text channel object and use the purge method on it
channel = bot.get_channel(channel_id)
await channel.purge(limit=100)
wait wahtttt
can you like show me an exampel?
I already did
well it didnt work
i think i need to add ehh like the 'purge' thingy
won't spoonfeed
spoonfeed?
yes
whats that
@bot.command()
async def purge(ctx: commands.Context, limit: int) -> None:
await ctx.channel.purge(limit = limit)
🛐 here you go
Good job
oh
......... well sorry i just dont know what spoonfeed means
well ty anyways
why doesnt it purge when i says !purge 2
On
@client.event
async def on_member_join(member):
welcomeRole = discord.utils.get(guild.roles, name = "Welcome")
await member.add_roles(welcomeRole)
guild.roles is not defind
how do you reset synced commands?
spoonfeed means he wont write the code for you. he will only help you on the way
and for slash commands?
ohhhhhhhhhhh
this github explains slash commands pretty well. https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#fundamentals-for-this-gist
member.guild.roles
I remember a while ago that someone wanted to create dual !command and /command where the command is the same, how do I do that?
for example: !help and /help
!d discord.ext.commands.Bot.hybrid_command
@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_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.Bot.add_command "discord.ext.commands.Bot.add_command").
Ty ty
@client.event
async def on_member_join(member):
welcomeRole = discord.utils.get(member.guild.roles, name = "Member")
await member.add_roles(welcomeRole)
if I want this also to send a message of welcome in the welcome channel what should I add?
you're not responding in time. You only have 3 seconds to respond to an interaction
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
welcome_channel=bot.get_channel(welcome_channel_id)
await welcome_channel.send("Your message")
Top of the call back
ctx?
ctx.response.defer()
ah
Ig he using ctx: discord.Interaction xd
how do you make a slash command admin only?
poor guy named app and client keeps getting pinged
U know better where completing tasks taking long
Where u need to do something long, then defer it before that task
How do I check if a message is sent to DM?
I cant to setup a system so when someone uses a command, the bot opens up chat with the user in DMs and asks them various questions.
Yes do it
@slate swan answer it or : 🔫
uhh
!d discord.DMChannel
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channel’s hash.
str(x) Returns a string representation of the channel
Oh yeah @drifting arrow
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.
What Database system you working with?
check
if isinstance(message.channel, discord.DMChannel):
Bruh man every time I try to play / stop / skip music bot it's just not working at all
In regards to the query, you need to ensure {ctx.guild.id} is the same type as serverID in your database
💀
Just do a simple print? print(type{ctx.guild.id}
also u didnt f string so it not gonna return guild id
or if you dont care either way, do guildid = int(ctx.guild.id) or guildid = str(ctx.guild.id)
!e
e=[]
print(type(e))
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'list'>
Ok u did pretty gud thing
WHAT THE HECK IS RESULT IF U DIDN'T EVEN declared
well not being rude xd
anyway love to stay and help but i got a discord bot to write! 😄
result=cursor.execute(...)
@slate swan
You know how to make bot playing music / stop / skip / stop / resume (just with song name) ? @shrewd fjord
Fix it or 🔫
So maybe if I need help you help me
...
I didnt make music bot so idk
Alright no problem
Oh nvm
I am being dumb 😂
@slate swan is it pycord???
Ok dawg
Wait no
Pycord's module name also as discord
Fk me being dumb today
How do I make my discord bot wait for message response?
Hm?
Like say my bot dms a user and asks "What color would you like your role to be?"
how do I make it wait for a response?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@drifting arrow
Wait like?
When a member dm a bot
Bot asks some ques right?
Then how's that related to slash
okay
Coz I want the user to do something like /changecolor then the bot dms the user "What color?"
and then waits for them to reply
lol
Im exploring all new territory here and I ran out of coffee
I c
I'll expand upon it to have other questions lol
Well it's possible
Idk anything about db so don't ask me
Asking me = 🔫
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
property icon```
Returns the guild’s icon asset, if available.
is there any way to change the bots prefix (using text commands) 'live' e.g. while it is still running?
such as .set-prefix > and now it uses > as the prefix, so >ping
the time is wrong
now = datetime.utcnow()
time = datetime.fromtimestamp(min(int((datetime.now() + timedelta(days=28)).timestamp()),int((now + timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).timestamp())))
what are u trying to do ?
whats the issue?
yea idk what ur code is doing
why would roles be an empty string?
why not use a list
Does anyone know how to make a music bot because I don't know at all and need to learn how to
can someone help?
maybe they were attempting “if roles:” so you could handle if there were none? idk looks odd
ya
It would be like this for editing original response?
@app_commands.command(name='ping', description="Shows the bot's latency in ms.")
async def ping(self, interaction: discord.Interaction):
""" use /ping for ping command"""
latency = round(self.bot.latency * 1000)
message = await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
await message.edit_original_response(content=f'\n{latency}ms ')
That didn't work
send_message doesn't return anything. You have to use Interaction.edit_original_response
though at that point simply add latency to the actual response?
Ya
i discovered
an additional way.
await inter.response.send()
msg = await inter.original_response()
await msg.edit()
Thank you even so
Oh
Thanks
Using asyncio.sleep() doesn't work
?
original_response 
like that
oh yeee
@app_commands.command(name='ping', description="Shows the bot's latency in ms.")
async def ping(self, interaction: discord.Interaction):
""" Use /ping for ping command"""
latency = round(self.bot.latency * 1000)
await interaction.response.send_message(f'🏓 Pong!\n...', ephemeral=False)
await asyncio.sleep(0.3) # Here
await interaction.edit_original_response(content=f'🏓 Pong!\n{latency}ms ')
why lmfao
idk
why aren't you sending the latency directly?
also ephemeral is defaulted to False no need to define it
I know
there are tests only
i'm testing many things
@fading marlin
I read the documentation, and I didn't really understand how to do it, returns an error name 'fetch_message' is not defined
@client.command()
async def cls(ctx, amount: int):
if ctx.author.guild_permissions.manage_messages:
deleted = await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"Messages Purged: {len(deleted) - 1}")```
When used, it does send the messages purged message, but there's a few seconds of delay before it does. The bot has a typical latency of 45 ms so that's not the issue
probably because purging might take some time?
It's been a while since I've messed with bots, but I've had another one a long while back, it was instant, the message. I love the sarcasm, but maybe tone it down?
I mean the simplest way to find out is to just time the methods
you're a prick. fuck yourself bitch
excuse you?
🤨
where did rawreactionactionevent.reaction go
Rude 😞
oh it was never a thing
how can i use this variable result or whatever, in another embed.
can you specify
my bot saves the users answer and posts in a embed, however how could i get this result in another buttons embed
that seems
way out of left field bruh
store it somewhere
preferably a database
something more simple
you can store it as a simple instance attribute
in a text file?
lol u again?
i need the same result just to be in another embed
like in the picture
😶🌫️
use a dictionary or smth
what about global variables
bruh
^
give me an exmaple
I have no idea what ur talking about
attr of the command?
Hi guys, just opened an help thread about loops not working, maybe someone here could have a look and point me in the right direction, thanks for your time =)
they're in a view, and they need to pass the value of one thing inside the callback of a button to another button. What's convenient is that both button callbacks are methods of the same view
class A:
def __init__(self):
self.value: str | None = None
def first(self, value: str) -> None:
self.value = value
print(f"Value has been set to {value}")
def second(self) -> None:
print(f"Value is currently set to {self.value}")
>>> a = A()
>>> a.second()
Value is currently set to None
>>> a.first("foo")
Value has been set to foo
>>> a.second()
Value is currently set to foo
msg = await interaction.client.wait_for("message", check=lambda m: m.author == interaction.user and m.content.isdigit())
x = (f"{int(msg.content)*0.0025}$")
embed = discord.Embed(title="Purchase Confirmation", description="", color=0xF1C40F)
embed.add_field(name="Purchase Quantity :", value=msg.content, inline=False)
embed.add_field(name="Price :", value=" ``" + x + "``", inline=False)
await interaction.channel.send(embed=embed, view=a())
await interaction.message.delete()```
can someone help?
techincally no, a class attribute would be something like this:
class A:
value: str = "class attribute"
unlike the previous example, you don't need an instance of A to access value
both buttons share the same class (view), so you can pass pretty much any values you want to either callback. What would matter is the order in which each button is called
new issue or same issue?
i need this x variable in another button, mind helping me rq
i have extreme skill issue)
you can implement something like this on your view
where the class A is your view, and first and second your buttons
would you be kindly enough to write me how it would look like 😭
no, I'm not going to spoon feed you. I can guide you through it though
i am barely understanding anything
actually, this might help you too https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py#L21-L40
lol yea
uk what I ment tho
bruh I thought he was using 2 commands
not two buttons
Have the view track the state and reference from instance variables on the view
In a button, self.view.foo = "bar"
This is where it breaks away largely from "discord bots" to just normal python programming and design
a ui.View is just like any other object that you can extend
Hi guys, is anybody here who could help me with a problem regarding loops? sent my code in #1052692833292796004
sent a response
are you crazy?
how it is possible to make request in a database outside of functions? (in cogs)
Can you elaborate more
what would that look like? I changed the code to what i assumed it would look like but it doesnt work
nah
can i explain how to do it?
not really that smart with coding, still learning btw
@client.tree.command(name='giveaway', description='Starts a giveaway')
async def giveaway(ctx: discord.Interaction):
await ctx.response.send_message("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?", "What should be the duration of the giveaway? (s|m|h|d)", "What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author.id == ctx.user.id and m.channel.id == ctx.channel.id
for i in questions:
await ctx.channel.send(i)
try:
msg = await client.wait_for('messsage', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.channel.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send_message(f"You didn't mention a channel properly. Do it like this {ctx.channel.mention} next time.")
return
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.channel.send("You didn't answer with a proper unit. Use (s|m|h|d) next time!")
return
elif time == -2:
await ctx.response.send_message("The time just be an integer. Please enter an integer next time.")
return
prize = answers[2]
await ctx.channel.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
embed = discord.embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
embed.add_field(name = "Hosted by:", value = ctx.author.mention)
embed.set_footer(text = f"Ends {answers[1]} from now!")
my_msg = await channel.send(embed = embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
why is it saying I didnt answer in time
how would I make a giverole command but where you can only give certain roles that are in a list if that makes sense
ik i could just do an eaasy variable but its 30+ roles
im trying to figure out how to make it shorter
im going to try to explaain the best I can. Pretty much this is a football sign bot. I want to make it where whatever team role you have, when you run the command, it gives the person you mentioned the team role that you have. Example im on team 1. I try to sign someone, it will automatically give them the team 1 role. But the thing that is hard is that there are 32 teams. So I can't just do 32 if statements.
so you are ready?
yea
@somber sky you can just do
if FORole or GMRole or HCRole in ctx.author.roles:
await ctx.send("I have the roles!")
else:
await ctx.send("I dont have roles!")
alr thanks
that gets evaluated as
if (FORole) or (GMRole) or (HCRole in ctx.author.roles):
you would probably be looking for any in this case
you know how to store ids (in db or json) ?
you should probably defer
nah lol
use autocomplete for the roles
max is 25 but you can do some tricks to allow more based on type matching
using autocomplete will remove the thousands of if statements you would be writting
@sick birch
we got a weirdo in here
noo don't make them take our image perms too!!
Dont ping Robin! Ping mods!
<@&831776746206265384>
!mute 1052634780937748570 spam
ahhh
:x: According to my records, this user already has a mute infraction. See infraction #83973.
!mute 1052634780937748570 
:x: According to my records, this user already has a mute infraction. See infraction #83973.
noice thanks
Slow 😔
(literally spam)
I love spam
troll = '<:trollface_left: 998951318133673984>'
@client.tree.command(name='test', description='custom image embed')
async def emb(ctx: discord.Interaction):
await ctx.response.send_message(f'{troll}')
why wont custom emojis work?
the actual format of custom emoji is <:name:id> i think
thats what I have
ok you just edited it
yea
Can someone help me understand why when I try to run my discord bot in my priv server it don't wanna actually function and respond with an answer?
heres the code import discord
client = discord.Client()
@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
def is_food(word):
KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS
# Check if the message contains the word "food"
if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.")
I have the client.run and the token for the bot
you need message intents on
you've got a space there
you are using a very outdated tutorial
they are on
doesnt send the emoji
its so it doesnt get blocked
"blocked"?
In the code too, i mean
auto fixes itself
:cat_sip:
add a backspace before instead?
:cat_sip:
make sure you got the emoji id, not the message id
I've got no clue what you're trying to do
trying to send custom emoji but it just sends the name
if I dont put a space it deletes the message
maybe its this
that's been fixed
then your bot simply doesn't have access to the emoji?
weird then
if I send the message ME not the BOT it deletes because I DONT have NITRO
thats why I put A SPACE in what I sent SO it DOESNT DELETE
your fine
What would that look like if you don't mind me asking?
here
I still don't get what happens when your bot sends the message though?
it doesnt send the custom emoji
it just sends the emoji name
@client.tree.command(name='test', description='custom image embed')
async def emb(ctx: discord.Interaction):
await ctx.response.send_message(troll)
I copied it to how it look on the documentation but still nothing
is the emoji from the same server?
no
does your bot have permissions to use external emoji?
and is the bot in the server which has the emote
what does your new code look like?
File "main.py", line 33
await ctx.channel.send(f"Signed {user.mention!}")
^
SyntaxError: f-string: invalid conversion character: expected 's', 'r', or 'a'
await ctx.channel.send(f"Signed {user.mention!}")
import discord
intents = discord.Intents(messages=True)
client = discord.Client()
@client.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == client.user:
return
def is_food(word):
KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS
# Check if the message contains the word "food"
if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.")
client.run(removed for obvious reasons)
@vagrant brook
!intents
never had this error
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.
you've got an exclamation mark inside an f-string
oh
thanks```py
@client.tree.command(name='sign',description='Sign a player.')
@app_commands.describe(user = 'pick a user')
async def sign(ctx: discord.Interaction, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
if FORole or GMRole or HCRole in ctx.author.roles:
await ctx.channel.send(f'Signed {user.mention}!')
if user.id != ctx.user.id:
name = list(nflRoleListNames)
roles = list(ctx.user.roles)
for name in roles:
if name == roles:
FORole = discord.utils.get(ctx.guild.roles, name=name)
await user.add_roles(role=name)
else:
await ctx.channel.send("You are not a coach.", hidden=True)
Trying to make it so that when you sign someone, it will give them the role that you have
I get no errors but it doesnt work
this
if FORole or GMRole or HCRole in ctx.author.roles:
is evaluated as
if (FORole) or (GMRole) or (HCRole in ctx.author.roles):
you'd probably be looking for something like this
if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
add_roles doesn't have a role kwarg either 🤔
me and him are doing it together, the thing thta isnt working is the role, the person u sign is supposed to get the team role you have but it doesnt do anything
no errors
you should probably be getting errors. Do you have an error handler that might be eating them up?
I dont have any
were both working on different projects and we both dont get errors
well, I've mentioned above a few things that might be causing issues
this is what i have
@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
await ctx.send("I have a role or more")
if user.id != ctx.author.id:
for role in nflRoleListNames:
if role in ctx.author.roles:
await user.add_roles(role=role.id)
else:
await ctx.send(f"You are not a coach.", hidden=True)
print("User was not a coach.")```
@fading marlin used those methods, they dont work, no errors
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
await ctx.channel.send(f'Signed {user.mention}!')
if user.id != ctx.user.id:
name = list(nflRoleListNames)
roles = list(ctx.user.roles)
for name in roles:
if name == roles:
name = discord.utils.get(ctx.guild.roles, name=name)
await user.add_roles(name)
Interaction.user.roles already returns a list, so I don't see why you're casting it to a list. Additionally, you're comparing Role to a list... which will always be false
if it returns a list, then why wont it work?
you're overriding name
name = list(nflRoleListNames) # list of something
roles = list(ctx.user.roles) # list of roles
for name in roles: # name is now a Role object
if name == roles: # comparing (Role == list[Role]) which is always false
ok, update
if "food" in message.content.lower():
# Check if the word is a known food or not
if is_food(message.content):
general_channel= client.get_channel(872336555182800948)
await message.channel.send("That's a real food!")
else:
await message.channel.send("I don't think that's a real food.") This part is what is screwing me up. how could I fix this.
I need KNOWN_FOODS = ["apple", "banana", "carrot", "pizza", "chocolate", "strawberry", "broccoli", "chicken", "beef", "fish"]
return word in KNOWN_FOODS to be a thing that when people type in any of these, it will either respond with either say yes its real or no its not a real food.
for name in list(roles)
so would it be for example for KNOWN_FOODS in message content lower
you want to check if a message contains any words given in a list?
yes
I need this list to be used to determine if any of the words in here are in a message, the bot would the respond with either= Yes: real food, or No: fake food.
Apparently how it was initially It was looking for just the word food and it would always say, no its fake food.
you can now @bright wedge
i will suggest you to use aiosqlite
!pip aiosqlite
enable external emoji perms for the everyone role
and for the bot role
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
roles = list(nflRoleListNames)
if ctx.user.roles in roles:
await ctx.response.send_message(f'found {roles}')
else:
await ctx.response.send_message(f"not found {roles}")
why is it saying not found
you're checking if a list is inside a list
how can I check if the authors roles is in the list of names
should they have all of the roles in nflRoleListNames or just one?
one
use the same expression you have above in your if-statement
?
any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles) but change the hardcoded list of roles to the nflRoleList one
place that under the if statement or replace it
you change it with the if statement that's checking if a list is inside a list
what is ctx.user
a badly named parameter. ctx is the injected Interaction
roles = list(nflRoleListNames)
if any(role in [nflRoleListNames] for role in (ctx.user.roles)):
await ctx.response.send_message(f'found {roles}')
else:
await ctx.response.send_message(f"not found {roles}")
oh lol
sure, though you don't need to surround nflRoleListNames in brackets, nor ctx.user.roles in parenthesis
send your updated code please
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
if any(role in nflRoleListNames for role in (ctx.user.roles)):
await ctx.response.send_message('found')
else:
await ctx.response.send_message("not found")
else:
await ctx.channel.send("You are not a coach.", hidden=True)
the full callback
like full code
@client.tree.command(name='sign',description='Sign a player.')
@app_commands.describe(user = 'pick a user')
async def sign(ctx: discord.Interaction, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
if any(role in nflRoleListNames for role in ctx.user.roles):
await ctx.response.send_message('found')
else:
await ctx.response.send_message("not found")
else:
await ctx.channel.send("You are not a coach.", hidden=True)
what exactly is nflRoleListNames?
nflRoleListNames = ["Arizona Cardinals", "Baltimore Ravens", "Atlanta Falcons", "Buffalo Bills", "Carolina Panthers", "Cincinnati Bengals", "Chicago Bears", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Houston Texans", "Green Bay Packers", "Indianapolis Colts", "Los Angeles Rams", "Jacksonville Jaguars", "Minnesota Vikings", "Kansas City Chiefs", "New Orleans Saints", "Las Vegas Raiders", "New York Giants", "Los Angeles Chargers", "Philadelphia Eagles", "Miami Dolphins", "San Francisco 49ers", "New England Patriots", "Seattle Seahawks", "New York Jets", "Tampa Bay Buccaneers", "Pittsburgh Steelers", "Washington Commanders", "Tennessee Titans"]
oh, then you have to get the name of the role on your second if-any stmt
how? im confused
role is an instance of Role, and Role has a name attribute
any(role in nflRoleListNames for role in ctx.user.roles)
this is basically the same as a for loop and can be re-written like so:
for role in ctx.author.roles:
if role not in nflRoleListNames:
return False
return True
perhaps that will make it a bit easier to comprehend
since you're iterating over a list of Roles, each item will yield a Role object. Roles have a name attribute which you can use to get the name of the role
almost
for role in ctx.author.roles:
if role.name not in nflRoleListNames:
return False
return True
how would you translate that to the other method? (any(...))
I just told you that any(role in nflRoleListNames for role in ctx.user.roles) is pretty much a 1-line for loop and I showed you how to represent it, right?
why you dont use role ids?
32 roles
im confused
I'm referring to this
yea what about it
this is what you need, but you have to "convert" it to the other way
for role in ctx.author.roles:
if role.name in nflRoleListNames:
return True
return False
this?
yeah, you just gotta pass that to the other any(...) way
if any(role in nflRoleListNames for role in ctx.user.roles):
for role in ctx.author.roles:
if role.name in nflRoleListNames:
await ctx.response.send_message('found')
else:
await ctx.response.send_message("not found")
no, going back to your previous code, in your second if statement
if any(role in nflRoleListNames for role in ctx.user.roles):
here, role is a discord.Role object
Roles have a name attribute which returns the role's name...
yea
sooooo
remove the if
there ya go :D
replace both role or just first one?
the second one, but yeah, not both
alr thanks ill test
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
if any(role in nflRoleListNames for role.name in ctx.user.roles):
await ctx.response.send_message('found')
else:
await ctx.response.send_message("not found")
else:
await ctx.channel.send("You are not a coach.", hidden=True)
Traceback (most recent call last):
File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 26, in sign
if any(role in nflRoleListNames for role.name in ctx.user.roles):
File "main.py", line 26, in <genexpr>
if any(role in nflRoleListNames for role.name in ctx.user.roles):
NameError: name 'role' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Configs-Bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'sign' raised an exception: NameError: name 'role' is not defined
oh, no, yeah, you add role.name to the first role. Sorry, I thought you were referring to the if statements
ok thanks ill try again lol
if any(role.name in nflRoleListNames for role in ctx.user.roles):
await user.add_roles(role.name)
what about adding a role?
which roles do you want to add?
the ones it found in my roles that are in the list
let's say you have the Arizona Cardinals role, what should the bot do?
add arizona cardinals to the guy you signed
add that role to the user I select if they dont have a role thats in the list
oh, alright, well you could use utils.find to get the role and add it
how would I get the name tho
how come when i put the same code here this happens?
File "main.py", line 113, in sign
if any(role in [FORole, GMRole, HCRole] for role in ctx.user.roles):
AttributeError: 'SlashContext' object has no attribute 'user'```
looks like you guys aren't using the same library
ctx.author.roles
maybe something like this?
find(lambda r: r.name in nflRoleListNames, ctx.user.roles)
why are you even using role names when IDs are easier to use and compare
THANKS GOD 😄
got it to work, thanks dude i appreciate it a ton
@fading marlin how come when the user doesn't have FO, GM, HC role it doesnt do anything but when it only has a coach role it says you are not a coach
@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.author.roles)
if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
if any(role.name in nflRoleListNames for role in ctx.author.roles):
await user.add_roles(teams)
else:
await ctx.send("You are not a coach.", hidden=True)
print("User was not a coach.")```
when ur not a coach it doesnt say anything
it shoiuld say u are nopt a coach
ooops wrong command
Make a list
No
Nvm u r doing to hardly tho
if FORole or HcRole in ctx.author.roles:
...
Hey i've never coded a discord bot and im just trying to see if im good at it or not. Anyone able to give me any pointers on how to start or the basics?
do you know any python basics?
yes.
you'll start with choosing a library for bot development discord.py ( or its forks) and hikari are some of the popular ones
probably discord.py
This is a Test to know if you are ready to make a bot using discord.py:
A: in your words, what is the purpose of a For Loop?
B: what is Blocking? and why do you have to use Async for a discord bot?
C: how do you know if a line of code is inside a Block or Scope (like a Function, Class, For Loop, etc...);
and how do you make that piece of code be outside of the Block or Scope?
D: if you have to make an HTTP Request with your bot, what Libriary would you use?
E: in your words, what is Object Oriented Programming (OOP) and how does it get used in python?
F: what are Fstrings (3.6+) and how can you use them to just get 2 Decimal Places of a Long Float?
G: what is Try-Except, and how can you use it to except Specific Errors?
H: how would you Force to get an Error in the case of not getting one (or atleast know where the problematic line is)?
I: what are the use case of Function Decorators? and what are they really in the background?
J: how would you store Multiple Pieces of Data that are related to more data? (Example: Name1 = James, Name2 = Steve, etc...)
here's some basic things you need to know about
you don't need to answer them here lol, but just have a look and you can evaluate yourself
ok
How would I make it where if they are on a different team it will not go through? @fading marlin
@slash.slash(description='Sign a player.')
async def sign(ctx, user: discord.Member):
FORole = discord.utils.get(ctx.guild.roles, name="Franchise Owner")
GMRole = discord.utils.get(ctx.guild.roles, name="General Manager")
HCRole = discord.utils.get(ctx.guild.roles, name="Head Coach")
channel = bot.get_channel(Transactions)
teams = discord.utils.find(lambda r: r.name in nflRoleListNames, ctx.author.roles)
signembed = discord.Embed(title='Franchise Signing', description =f'{teams.mention} have **signed** {user.mention}`{user}`\n\n > **Coach:** {ctx.author.mention}`{ctx.author}`\n> **Roster:** 0/24',timestamp = datetime.datetime.utcnow())
signembed.set_footer(icon_url = ctx.author.avatar_url, text='{}'.format(ctx.author))
signembed.set_author(name=f"{ctx.guild.name} Transactions", icon_url=f"{ctx.guild.icon_url}")
if any(role in [FORole, GMRole, HCRole] for role in ctx.author.roles):
if teams in user.roles:
await ctx.send(f'User is already on the {teams.mention}', hidden=True)
await ctx.channel.delete(embed=signembed)
if any(role.name in nflRoleListNames for role in ctx.author.roles):
await user.add_roles(teams)
await ctx.send(f"Signed {user.mention}", hidden=True)
await channel.send(embed=signembed)
else:
await ctx.send("You are not a coach.", hidden=True)
print("User was not a coach.")```
Hi. I want my Discord bot to have a slash command as well as normal command that can be executed with the bot prefix. But I don't want to use hybrid commands as rewriting will take a lot of time tho.
So my question is,
How do I make a slash command with
bot = commands.Bot(command_prefix=get_prefix, intents=intents, case_insensitive=True, help_command=None)
(im sorry if it's very complicated to understand.)
how do i use ctx.guild.members is im using slash command?
@tree.command(name = 'stuff', description = 'do stuff')
async def stuff(interaction: discord.Interaction)
for members in
!d discord.Interaction.guild
property guild```
The guild the interaction was sent from.
thanks
how about sending message to the person that runs the command?
interaction.user.send
send it ill try to help
@bot.command()
async def testform(ctx):
form = Form(ctx,'Title')
form.add_question('Question 1','first')
form.add_question('Question 2','second')
form.add_question('Question 3','third')
result = await form.start()
return result
Anyone know of something similar for discord.Interaction/app_commands
ah yes
who uses Form though? That seems rather opinionated for something Discord might expand on later
I guess right now it kind of works... until they add support for another component 😄
i'm trying to make a bot when the user uses !image <cat> or whatever it just google it and use the first image and save the url to my sheety spreadsheet, the issue is its detecting the onmessage event and after that its coming to client.run(), its not going through the remaining lines of code.please help me ❤️
I see nothing wrong
What's the problem
Also use a async http client instead of requests
Also wait
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
am trying to put a streaming activity on my bot but its showing
AttributeError: 'Command' object has no attribute 'Streaming'
here is the code:
await client.change_presence(activity=discord.Streaming(name="streaming", url="https://www.twitch.tv/#"))
don't make a command function called discord
discord.ui.TextInput
Does anyone know how to convert the result of a modal to an integer? I am trying to subtract the result by a number but it gives this error
- TypeError: int() argument must be a string, a bytes-like object or a real number, not 'TextInput'
I tried to add int but the result still does not convert
rank = self.rank
rank = rank - 100
print(rank)
I tried to add a style attribute so the result is already an integer but it seems like the only three options are short, paragraph, and long
rank=int(rank) - 100
print(rank)
Ez as that
!d discord.ui.TextInput.value
property value```
The value of the text input.
🆒
that didnt work but that seems like it ^
rank=str(self.rank)
rank=int(rank)
Just try 💀
Or just get the value from it then convert
makes sense
when i added the str in the first part it worked thank you
nice
how can I check if someone's discord account is over 14 days old
time delta
done solution found
good
yeah but how do i get the time their account was made
and other error last final:
async def whois(ctx, *, user: discord.Member = None):```
thanks
member.created_at
this ^
full error
name="whois"
okay
slash command's name can't be uppercase
yep
really?
ofc
only example "m", not "M"?
yep
hmm ok check.
on docs u will find the conditions
like ig 32 is max character
Ask Discord why they don't allow it
i forgot
api limitations :
i see.
oh other error said: @client.tree.command(name="buypremium", description='Buy Premium SuperKenos') async def premium(ctx, self):".
TypeError: parameter 'self' is missing a type annotation in callback 'premium'
remove self parameter
it's not cog neither a class
nice
okay testing.
I'm not a database expert 🐈
ah shit
But probably SQLite databases or mongodb
Cool, Thanks for ur suggestion ;]
age = datetime.utcnow() - user.created_at
TypeError: can't subtract offset-naive and offset-aware datetimes
@shrewd fjord i see problem there error red "discord.app_commands.errors.CommandNotFound: Application command 'show-manager-channel-testing' not found"
await interaction.response.send_message(embed=embed)
but if I do datetime.datetime.utcnow() I get an error aswell
!d discord.utils.utcnow
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
ctx change think "interaction: discord.Interaction"
did u syncur commands?
yes have
it's ur wish how u decorate discord.Interaction
also it's positional parameter so np
yeah is slash commands
ccan u show the slash command?
Thanks
@shrewd fjord have same error red
sigh ok code:
remove @commands.has_role
nop, have my role is okay.
slash command's is totally diff from normal commands
That's probably for prefix commads
hmmm
yep
anyone know the fastest way to scrape someones newest tweet?
!d discord.app_commands.checks.has_role
.. sigh ok
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
moment
@commands.has_role("Channels Manager")
async def show_manager_channel(ctx):
embed = discord.Embed(
title="⚙️ CHANNELS MANAGER | SUPERKENOS ⚙️", colour=0xAC00FF)
cur.execute("SELECT * FROM x WHERE x =%s",
(ctx.guild.id,))
configured_channels = cur.fetchone()
#print(configured_channels)
if configured_channels == None:
await interaction.response.send_message("A first show manager channel must be configured **/update-manager-channel** ⚠")
return
#print(f"Suggest ID = {suggest_channel[1]}")
embed.add_field(name="💡 Suggest", value=f"<#{configured_channels[1]}>")
#print(f"Giveaway ID = {suggest_channel[2]}")
embed.add_field(name="🏆 Giveaway", value=f"<#{configured_channels[2]}>")
embed.add_field(name="🥇 Role Giveaway",
value=f"<@&{configured_channels[3]}>")
# change update
embed.set_footer(
text="📝 Change to channels this command /update-manager-channel")
embed.set_footer(
text="🚨 Don't forget to create role ´ Channels Manager - Giveaways Manager´ has been can permission command")
await interaction.response.send_message(embed=embed)```
try explain exactly?
but my little understand hard
i am no good english and little english
my spanish.
and no experience "docs"
also, just dont name things like interaction ctx
it just causes confusion and is on top of that, pointless
example ctx, interaction?
and
from discord import app_commands
@tree.command()
@app_commands.checks.has_role()
ahh
async def command_name(interaction), rather then naming "interaction" "ctx"
Ok but first spokky.
again telling whatever u give parameter at first of slash command function
bad error
ok second
it directly converts to discord.Interaction
Ah remember, but same error.
as because u have to change all interaction to ctx or change ctx params to interaction
u have this 2 options
already same error.
new code?
try copy and page fix @shrewd fjord
yes.
think is @app_commands.checks.has_role("Channels Manager")
maybe?
@client.tree.command(name="show-manager-channel", description='Show a manager channel testing')
@discord.app_commands.checks.has_role("Channels Manager")
async def show_manager_channel(interaction):
embed = discord.Embed(
title=":gear: CHANNELS MANAGER | SUPERKENOS :gear:", colour=0xAC00FF)
cur.execute("SELECT * FROM x WHERE x =%s",
(interaction.guild.id,))
configured_channels = cur.fetchone()
#print(configured_channels)
if configured_channels == None:
await interaction.response.send_message("A first show manager channel must be configured **/update-manager-channel** :warning:")
return
#print(f"Suggest ID = {suggest_channel[1]}")
embed.add_field(name=":bulb: Suggest", value=f"<#{configured_channels[1]}>")
#print(f"Giveaway ID = {suggest_channel[2]}")
embed.add_field(name=":trophy: Giveaway", value=f"<#{configured_channels[2]}>")
embed.add_field(name=":first_place: Role Giveaway",
value=f"<@&{configured_channels[3]}>")
# change update
embed.set_footer(
text=":pencil: Change to channels this command /update-manager-channel")
embed.set_footer(
text=":rotating_light: Don't forget to create role ´ Channels Manager - Giveaways Manager´ has been can permission command")
await interaction.response.send_message(embed=embed)```
up missing
lol
;-;
oh i see think spooky missing "checks" 
discord.app_commands.errors.CommandNotFound: Application command 'show-manager-channel-testing' not found
error same sigh no solution?
do you have any logs saying you're ratelimited when you restart your bot @severe mural
edited again xd
any error on discord?
like oudated
yes
tell
:/
hmm restart bot?
kick and again back bot?
but already have ctrl + C offline again terminal.
no
ah ok
restarting on code
make sure your appcommands scope enabled on dev portal while inviting
short the name and try again
yes have.
name?
name="show-manager-channel", description='Show a manager channel testing') think?
yes
but this shouldn't be the problem tho
hmmm
just try ig
how is xd
Okay try.
also make sure u didnt made any typo mistake on has_role
@shrewd fjord i see
think no found show-manager-channel-testing but addd there
is okay solution. Maybe yes restart bot kick and back bot
change name
think.
but maybe cache discord
moment try investigate
thanks help @shrewd fjord @flat pier @naive briar
nice
