#discord-bots
1 messages · Page 327 of 1
show code
@slash1.autocomplete('iskola_neve')
async def slash1_autocomp(interaction:discord.Interaction,courent:str)->list[app_commands.Choice[str]]:
options=[]
global KLIK_OPTIONS
if 'kliks' not in globals():
KLIK_OPTIONS=get_kliks()
for name, value in KLIK_OPTIONS.items():
if courent.lower() in name.lower():
options.append(app_commands.Choice(name=name,value=value))
if len(options)>=7:
break
print(options)
return options
the dict in KLIK_OPTIONS has like 4900 elements but the print shows that it is fast enught
try using return options[:25]
that didnt fix it
nothing seems to change the loop already stops at 7
if len(options)>=7:
if it helps this is one of the list discord sayid loading options failed for
[Choice(name='Földi János Két Tanítási Nyelvu Általános Iskola és Alapfokú Muvészeti Iskola Szilágyi Dániel Úti Tagintézménye', value='klik031049006'), Choice(name='Egri Szilágyi Erzsébet Gimnázium és Kollégium', value='klik031598001'), Choice(name='Egri Szilágyi Erzsébet Gimnázium és Kollégium Tagintézmény', value='klik031598101'), Choice(name='Budapest I. Kerületi Szilágyi Erzsébet Gimnázium', value='klik035219001'), Choice(name='Miskolci Szilágyi Dezso Általános Iskola', value='klik028978001'), Choice(name='Miskolci Szilágyi Dezso Általános Iskola Görömbölyi Tagiskolája', value='klik028978003'), Choice(name='Berettyóújfalui SZC Szilágyi Dániel Gimnáziuma, Szakgimnáziuma és Szakközépiskolája', value='beszc-szilagyi')]
i found it it turns out schools in hungary can have more than a 100 letters witch is the limit for Choices names lengths for example:
Földi János Két Tanítási Nyelvu Általános Iskola és Alapfokú Muvészeti Iskola Szilágyi Dániel Úti Tagintézménye
witch is 111 letters
You should be. Show your code
Unless you’re using Literal[]
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
create_ticket doesn't have any code, just comments
@ashen notch I was going to add a list of users who are not queued up under the one that is queued up. What can I title this list?
Nvm I could just add two emojis ✅ ❌ grab every user in voice channel and then check if they are in queue or not
anyone tried sillydev site before to host a bot?
it's not letting me install dotenv python package
idk i might've messed up
should i send the error message in the console here? it's so long
okay this will say enough i guess
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
[notice] A new release of pip is available: 23.2.1 -> 23.3.1
[notice] To update, run: pip install --upgrade pip
Traceback (most recent call last):
File "/home/container/main.py", line 1, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
Silly Development: Server marked as offline...
[Pterodactyl Daemon]: ---------- Detected server process in a crashed state! ----------
[Pterodactyl Daemon]: Exit code: 1
[Pterodactyl Daemon]: Out of memory: false
[Pterodactyl Daemon]: Aborting automatic restart, last crash occurred less than 60 seconds ago.
i guess it says that dotenv is not installed? even tho it should be since i typed it in the python packages place in the site ummmm
Buy a real VPS like hetzner
All those hosting sites are trash
i dont wanna spend money on my first discord bot that doesnt do much at all lol
but i get your point thank you
It has been said a million times before, and will continue to be said. Free hosting sites are terrible as hosting inherently costs money. They all have major drawbacks, such as shared IPs which can get your bot cloudflare banned, hosting sites having access to your token and in certain cases them actually owning your bot
The issue you’re having is directly linked to your host choice. You haven’t even started your bot yet but you’re already running into issues due to it
hi
alright thank you
who uses turtle py for game dev
its undefined cause you never created such varriable?
Are you asking how to define a variable?
How is it confusing
In Python variables are defined with the = operator
Defining variables is one of the first things you learn when using Python. I’d highly recommend learning the basics before creating a discord bot as discord.py isn’t designed to be a beginner library
How can I grab all the users from a voice channel and compare it to a list?
Hello I have the code of a python bot connect to save the world on fortnite and the bot works but as soon as I execute a command the bot does not respond, can you help
!d discord.VoiceChannel.members
property members```
Returns all members that are currently inside this voice channel.
Does Fortnite allow robots to automatically join their game and collect rewards?
Of course but here the problem is that hardly I make a basic command like a /help the bot doesn't answer
Something like this?
voice_channel_id = 712072729406472374
voice_channel = ctx.guild.get_channel(voice_channel_id)
members_in_channel = voice_channel.members
= is used for assignment
Also tias
Should I sort the list by those in the queue and those who are not?
Having trouble getting guild object, passing the right id but the guild is still None somehow. Any suggestions?
class TicketBot(commands.Bot, View):
def __init__(
self,
initial_extensions: list[str],
guild_id: int,
):
super().__init__(command_prefix='', intents=discord.Intents.all())
self.initial_extensions = initial_extensions
self.guild_id = guild_id
async def on_ready(self):
await self.change_presence(activity=discord.CustomActivity(name='👀 Waiting for tickets'))
print(f'{self.user.name} is ready')
async def setup_hook(self) -> None:
for extension in self.initial_extensions:
await self.load_extension(extension)
print('loaded!')
# Here I am trying to get guild object
self.tree.copy_global_to(guild=self.get_guild(self.guild_id))
await self.tree.sync()
Cache isn't populated on setup_hook, so get_* will always return None. Also don't automatically sync, it's not recommended
how do I sync then?
Use an owner-only prefix command
took the thing from examples on git, they always put it either in on_ready or setup_hook
lemme search it up on docs
You don't need to sync every time you start your bot, and it's an easy way to get ratelimited
can you send examples or link to the docs where it is mentioned?
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
Implementation details (for sync command): https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
thanks a lot
but it seems to not sync the command from my cog
Did I set it up correctly?
# COG
class Ping(commands.Cog, name='Ping Command'):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(self.get_app_commands())
@commands.command(name='ping', help='Ping the bot!')
async def ping(self, interaction: discord.Interaction):
bot_latency = round(self.bot.latency * 1000)
await interaction.response.send_message(f'Latency is: {bot_latency} ms')
async def setup(bot):
await bot.add_cog(Ping(bot))
# run.py
async def main():
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
exts = []
for file in os.listdir(os.path.abspath('bot/cogs/commands')):
if file.endswith('.py') and file != '__init__.py':
cog = f'bot.cogs.commands.{file[:-3]}'
try:
exts.append(cog)
print(f'{cog} is initialized')
except Exception as e:
print(e)
for file in os.listdir(os.path.abspath('bot/cogs/events')):
if file.endswith('.py') and file != '__init__.py':
cog = f'bot.cogs.events.{file[:-3]}'
try:
exts.append(cog)
print(f'{cog} is initialized')
except Exception as e:
print(e)
print(exts)
async with TicketBot(
initial_extensions=exts,
) \
as client:
await client.start(token=bot_token)
asyncio.run(main())
You have no application commands in the cog
yeah I found it already, thanks 
!e you can't call sets 🤷
{1}()
@naive briar :x: Your 3.12 eval job has completed with return code 1.
001 | /home/main.py:1: SyntaxWarning: 'set' object is not callable; perhaps you missed a comma?
002 | {1}()
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 1, in <module>
005 | {1}()
006 | TypeError: 'set' object is not callable
Is {str}(selection) supposed to be str(selection)?
you're trying to call a coroutine inside a nromal function.
Is there any way I could simplify/improve this code?
# Get the voice channel
voice_channel = ctx.guild.get_channel(712072729406472374)
# Sort users_queue by ready_time
users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))
# Separate users into "Ready" and "Not ready"
ready_users = [member for member in voice_channel.members if member in [user["member"] for user in users_queue_sorted]]
not_ready_users = [member for member in voice_channel.members if member not in [user["member"] for user in users_queue_sorted]]
# Create strings for "Ready" and "Not ready" users
ready_string = '\n'.join([f'{member.mention}' for member in ready_users])
not_ready_string = '\n'.join([f'{member.mention}' for member in not_ready_users])```
this is probably faster tbh than iterating everytime ```py
members_in_queue = [user["member"] for user in users_queue_sorted]
ready_or_not_users = {}
for m in voice_channel.members:
ready_or_not_users.setdefault(m in members_in_queue, []).append(m)
ready_string = '\n'.join([f'{member.mention}' for member in ready_or_not_users[True]])
not_ready_string = '\n'.join([f'{member.mention}' for member in ready_or_not_users[False]])
maybe use a set for members_in_queue
can you show full traceback?
is one of your extension importing main file or something?
What about?
# Separate users into "Ready" and "Not ready"
ready_users, not_ready_users = [], []
for member in voice_channel.members:
(ready_users if member in (user["member"] for user in users_queue_sorted) else not_ready_users).append(member)
# Create strings for "Ready" and "Not ready" users
ready_string = '\n'.join(member.mention for member in ready_users)
not_ready_string = '\n'.join(member.mention for member in not_ready_users)```
@golden portal Or what about:
# Extract members in the voice channel
channel_members = set(voice_channel.members)
# Find members in users_queue_sorted
ready_members = channel_members.intersection(user["member"] for user in users_queue_sorted)
not_ready_members = channel_members.difference(ready_members)
preferred
also generator are slower than list comp, so better use list comp when possible
What about to make it as simple as:
# Get the voice channel
voice_channel = ctx.guild.get_channel(712072729406472374)
# Sort users_queue by ready_time
users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))
# Get sets of members for "Ready" and "Not ready"
all_members = set(voice_channel.members)
ready_members = set(user["member"] for user in users_queue_sorted)
not_ready_members = all_members - ready_members
# Create strings for "Ready" and "Not ready" users
ready_string = '\n'.join(member.mention for member in ready_members)
not_ready_string = '\n'.join(member.mention for member in not_ready_members)
i mean, you're essentially doing the same thing tbh, it's up to you to use which one
Which one would you use? Still the one you provided?
this i guess?
I think there's some sort of circular import going on here
Nevermind discord teleported me again
Who used railway?
can you help me
you completely skipped the actual error message so i doubt any1 knows how to help you
you cant install os since its built in module
datetime is built in too
I'm blind, can you show me where in the console it wrote about datetime, so that I could also see the next error, it just kicks out again and I don't understand anything.
is an hour of annotations unnecessary?
Than ask the question or make a channel in #1035199133436354600
can someone help me
I may can
ok, i have code but on my pc doesnt work, can i send you the code and you send me the results, screenshoots ?
I got almost no time rn
U may want to fix ur pc or make a channel in #1035199133436354600
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
how fix it on railway
it couldnt find the module ur trying to import either it dosent exist or its not on correct path
it's not even in my project.
well then python couldnt find the module called kafu_online_admission_system
What does he need it for and where should he put it?
idk thats for the guy who made the code to figure out
i have a ticket bot system running on my server. it starts when a user reacts to the msg on a channel that has ✉️ emoji. the bot is hosted on aws. but whenever i check back after 1-2 days, the react stops working bg and i’ve to generate a new embed for the bot to start working. why does this happen and is there any better alternative solution for ticket bot?
Which event are you using?
@commands.slash_command(name='timely', description='Получить ежедневную награду')
async def timely(self, interaction):
await self.db.create_table()
sender = interaction.author
# Check the last claim time from the database
last_claim_time = await self.db.get_last_claim_time(sender)
# Calculate the time elapsed since the last claim
current_time = datetime.datetime.now()
time_elapsed = current_time - last_claim_time
# Check if at least 24 hours have passed since the last claim
if time_elapsed.total_seconds() >= 24 * 60 * 60:
# Update the last claim time to the current time
await self.db.update_last_claim_time(sender, current_time)
# Update the user's balance
await self.db.update_money(sender, +30, 0)
# Send a message about the successful transaction
embed = disnake.Embed(color=0x2F3136, title='Временная награда')
embed.description = f'> **Вы успешно получили временную награду**\n'
embed.set_thumbnail(url=interaction.author.display_avatar.url)
await interaction.response.send_message(embed=embed)
else:
# Calculate the time remaining until the next claim
time_remaining = datetime.timedelta(seconds=(24 * 60 * 60 - time_elapsed.total_seconds()))
# Send a message about the time remaining until the next claim
await interaction.response.send_message(f'{sender.mention}, вы уже получали награду. Приходите через {time_remaining}.')
help me pls
get_last_claim_time ur db object dosent have any such method
Can someone help me to install like discord.py for windows?
just pip install?
idk i have no clue at all probably
have u installed python?
yh
which version
most recent
3.12?
No, the stable one.
and what was the error
copy paste the error here or send a pic
command prompt
this one?
python -m pip install discord.py
then u dont have it installed
Okay, how do I install it? (I thought I did)
A hands-on guide to Discord.py
Thanks.
are you able to help any more? this is what i have now.
worked tysm
np
what now?
how do I open it?
kk
wha-
i have never been more confused lol
how do I make a new file?
and what is visual studio code?
kk yeah just wanted to ensure i was right since that guide is kinda confusing ngl
https://code.visualstudio.com this one?
im kinda regretting trying to code my bots in python rather then using botghost lol
FYI discord.py isn’t a beginner library so without the prerequisites you’re going to have a lot of trouble
yeah but like i have no use but for discord bots so best way to learn
i can read docs
the install was just confusing me so much lol
Creating discord bots is definitely not the best way to learn as you’ll need to employ 20+ concepts just to create something simple
ehh, sound confusing and i like it
@bot.command()
@commands.is_owner()
async def reload(ctx, extention): # .load eco
bot.reload_extension(f"cogs.{extension}")
how do I fix it?
the error message says it came from your reload command... did you type .reload or .reload eco?
btw load_extension() and reload_extension() need to be oops that's for discord.py, not disnakeawaited too
ImportError: cannot import name '_shorten' from 'discord.utils
what's going on, should we wait for any updates?
can you show the full error message? import errors like this usually mean you have one or more conflicting libraries installed
File "F:\everydayuse\timestamp.py", line 1, in <module>
import discord
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\__init__.py", line 23, in <module>
from .client import *
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 67, in <module>
from .state import ConnectionState
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\state.py", line 62, in <module>
from .raw_models import *
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\raw_models.py", line 32, in <module>
from .app_commands import AppCommandPermissions
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\__init__.py", line 12, in <module>
from .commands import *
File "C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 60, in <module>
from ..utils import resolve_annotation, MISSING, is_inside_class, maybe_coroutine, async_all, _shorten, _to_kebab_case
ImportError: cannot import name '_shorten' from 'discord.utils' (C:\Users\PC\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\utils.py)
either way, the command code is the same.
Can you run pip show discord.py in the terminal?
and why I should do that?
eh they definitely have discord.py>=2.0, but i suspect either py-cord or nextcord is installed
if you have either of those packages, uninstall them alongside discord.py, then reinstall discord.py
do you have py-cord or nextcord installed?
let me check
what was the cmd to check which ones u installed
pip list
only discord.py 2.3.2
Run pip freeze and show the output please
pip freeze is the same as pip list
The only package you have installed is discord.py?
along the others like pyglet colorama etc
Can you show the entire output please?
sure but does that help me ?
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
that seems fine, how did you reinstall discord.py?
pip uninstall discord.py
pip install discord.py
Did you do any special commands/flags to install aiohttp, or was it automatically installed when you installed discord.py?
all auto
he seems to be using python 3.12 iirc dpy dosent support 3.12 does it?
it does not
discord.py does, aiohttp was having issues
yeah deps
aiohttp can be installed with custom wheels though, but I guess he didn’t do that
should I reinstall aiohttp ?
aiohttp 3.9.0 released some time ago so that should be fine with 3.12
he has 3.7
What’s the command to check the interpreters installed on the system again?
py -0 iirc
i mean i wouldn't be worried about it given that the earlier error message indicates it came from 3.12's global site-packages
C:\Users\PC>py -0
-V:3.12 * Python 3.12 (64-bit)
try pip install -U aiohttp
The issue is with discord.py itself
_shorten does exist in discord.utils, so there shouldn’t be an import issue
^ tbh i don't know why your discord.py install would still be corrupted after a reinstall
let me reinstall everything and check again i guess
do u have a folder/file named discord or smn?
Which is better for hosting discord bots? Linuix Or Windows?
linux
irrelevant imo
Doesn’t really matter
How to make 💰 using discord bots ?
pretty hard
If you have a capable server and internet the speed differences from location to location will be small
technically does matter cause if its for hosting services why waste memory for hosting windows server
since discord bot markets are very saturated
while you can be running on some debian
Referring to the location question
Any other ways
ah
Really depends on what type of bot you have
What type does it work ?
So like a uk linux vps would run near enough the same speed as a USA one?
speed of what
ping
its hard to tell it depends on the data center hosting the vps
usually its uniform
should I just install 3.9 python?
3.11 if so
Are you asking how to monetise your current bot, or how to create a bot that produces income
Mostly both cases would be helpful
I dont really have a useful bot but I'm working on one that is not gonna make any money
3.10 for the win I guess
@bot.command()
@commands.is_owner()
async def reload(ctx, extention): # .load eco
bot.reload_extension(f"cogs.{extension}")
Help how to fix this
What bot are you working on
how did u use the command
You’re not passing any arguments when invoking the command
u forgot to pass the extension name when using it
extention is a required argument
At this stage creating a bot for money isn’t profitable unless it’s an extension of an already existing business
how can I loop through and create a button for each item in a dictionary?
Talk me more
Which part are you asking for help with
Like how do I create the button?
I know how to create individual buttons, but I want to loop through each item in my dictionary to create a button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
These would then be added to the discord.ui.View instance
Where do I host my discord bot for free 24/7
you dont
Well replit does that ;_;
how is replit a hosting service
You use replit and uptimerobot and keep_alive.py
and how does that make it a hosting service
A hosting service does not require you to ping a web server thats run alongside your bot to keep the connection alive
!d discord.ui.Modal < @spark nimbus
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Thx
If I have a command that has buttons and I want to edit the original message when a button is clicked how do I do that?
I'm using the on_reaction_add event
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
is discord.py still actively maintainend ?
yes
Yes bro
thanks
Why am I getting a warn for the following line:
actual_reason = lowercase_preset_reasons.get(reason.lower(), reason)```
After the Pycharm update
how to add the python bot to a server
just invite it with the link you get in the discord developer portal
Its related to your type manager extension
Do I ignore it? How do I fix it?
Because StringLiteral is security type
To ensure unwanted people don't put unwanted stuff into unwanted places
You can ignore it if your case allows you to, but you'd rather ensure string passed there doesn't pose security vulnerability
I.e. choice of string is limited
!d typing.LiteralString
typing.LiteralString```
Special type that includes only literal strings.
Any string literal is compatible with `LiteralString`, as is another `LiteralString`. However, an object typed as just `str` is not. A string created by composing `LiteralString`-typed objects is also acceptable as a `LiteralString`.
Example...
Here is my code:
preset_reasons = {
"NSFW": "No NSFW or inappropriate content. This includes pornographic material, foul language, violence, and any other content that is widely found to be offensive and not suitable for public environments.",
"Spam": "Do not spam or otherwise misuse any channels. Keep content in their respective channels. Prevent yourself from splitting words or use several lines to say very little (line splitting)."
}
lowercase_preset_reasons = {key.lower(): value for key, value in preset_reasons.items()}
actual_reason = lowercase_preset_reasons.get(reason.lower(), reason)
@vale wing Do you have any idea how I can fix this?
actual_reason = str(lowercase_preset_reasons.get(reason.lower()), str(reason))
a bit odd that pycharm inferred the type that way, but regardless you can override the typehint yourself to mark dict keys as str, i.e. preset_reasons: dict[str, str] = ... (syntax assuming python>=3.9)
Thank you 
If I have a command that has buttons and I want to edit the original message when a button is clicked how do I do that?
Use interaction.edit_original_response() inside your button's callback.
i was going through your localization tutorial here for the actual translations do we have to do them manually?
A guide to internationalization with Python and discord.py. - thegamecracks/discord.py-i18n-demo
ie the msgstr string
oui, gettext assumes you or someone else can translate your program to the given locale
ah now that makes sense 💀 i was thinking get text does it for me
well if thats the case whats the point of the comments 😂
now time to work on a translation script btw i have doubt when i direcly used some translations from google translate it lead to discord not liking some of the characters prolly due to charset does gettext help with that?
Translators find it easier to provide an appropriate localization when they know the context of each message being translated. As such, adding comments beside messages is a helpful practice.
sometimes asking a person to just translate a string like "roll" isn't enough, for example which meaning of roll are they referring to? is it a food item, an action, or an adjective for another noun?
tbf the comment i wrote there also doesn't really give that context 🙃
bro ngl i thought gettext did the translations and not some other person ;-;
it happened in the msginit i assumed
fair enough, i'll amend the document to clarify that
so i got confused for a period of time
gettext is apparently 33 year old tech
btw another part u can include is the parts of gettext (msginit) dosent come with the usual git bash i had to install git sdk and pacman install gettext to get it so while the .po file will generate it will still give a few trivial errors
dumb of me ;-;
Is py from src.utils.generic import * inside an __init__ ethical to do?
yeah make sure to declare an __all__ in the generic
oh lol thought this was #python-discussion lel
thats usually what libs often do
all?
I guess I could
specifies a list of valid imports for linters altho if they want to import it it wont actually raise any error during runtime
huh that's weird, all the gettext programs i've mentioned i could use from git... msginit.exe straight up wasn't in C:\Program Files\Git\usr\bin?
parts of it a few sh scripts which were supposed to be in usr/share were missing
ah.. I'm asking since ruff is crying about it
src\utils\__init__.py:1:1: F403 `from src.utils.generic import *` used; unable to detect undefined names
these ones were missing for me
ur already in directory can u not do from generic import *
Yeah I just did but still the same result.
src\utils\__init__.py:1:1: F403 'from .generic import *' used; unable to detect undefined names
"Going to close for now because I'm comfortable with our current behavior." bruh
did u declare __all__ in generic?
Yep
declare one in init too
hmm weird tbh just mark it as # noqa: F403
It's going into the ignore list how about that

# Ignoring
# `no-blank-line-before-class` (D211) in favor of `one-blank-line-before-class` (D203)
# `multi-line-summary-first-line` (D212) in favor of `multi-line-summary-second-line` (D213)
ignore = [
"D211", "D212", "D100", "D101", "D102", "D103", "D104", "D107",
"ANN101", "ANN002", "ANN003", "D205", "D401", "E501", "TRY003",
"EM102", "ANN401", "G004", "SLF001", "D105", "F03"
]
``` got a nice list already.
damn
select = [
"F", "E", "W", "C90", "I",
"N", "D", "UP", "ANN", "S",
"BLE", "FBT", "B", "A", "COM",
"C4", "DTZ", "EM", "ISC", "ICN",
"G", "PIE", "T20", "PYI", "PT",
"PT", "Q", "RSE", "RET", "SLF",
"SIM", "TID", "TCH", "INT", "ARG",
"PTH", "ERA", "PD", "PGH", "PL",
"PLC", "PLE", "PLR", "PLW", "TRY",
"NPY", "RUF"
]
``` don't be fooled I do have a lot of rules but some are just bs
Forcing a comment on every function should be illegal.
fair
ahh those /usr/share warnings, i forgot about them
running into some unicode encode errors any idea on how to deal with those? i am not really sure since the charsets of languages are not utf-8 so getting errors
can you make a #1035199133436354600 post and paste the error message?
yeah I'll get to it again tmrw its like 3am here lmao sorry
oh lol, gnighty then
does anyone know why my bot replys so late? It has 30ms ping and no errors but it replys like a min after its on a linux vps
could be stuck on anything really, have you tried adding logging/print statements across your command to see where it's holding up on?
Ooops, It was a command what i haven't finished and i think that was it so i've just commented it out
How did it still respond then
The event decorator shouldn't be called
meaning, remove ()
I am attempting to create a discord/ game bot for a VR game using console commands within that game. My problem is is that I would like to automate the process of inputting usernames within that game so that way users can not abuse the system. The way it would work be by a user executing a “!link username” command. The bot would then give them a random string of letters in game and then they would follow the command up by doing “!link code”. This part I understand how to do, my problem is that I do not know how to make a variable have different values based on who executes it.
Use a dictionary to map each user to their own value.
What’s the difference between a dictionary and a database?
Dictionary is a data structure, database is a data storing service
Can't compare really
/keith mock/
What error
`C:\Users\abhay\OneDrive\Desktop\scanner>python main.py
Traceback (most recent call last):
File "C:\Users\abhay\OneDrive\Desktop\scanner\main.py", line 32, in <module>
@bot.hybrid_command()
^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'hybrid_command'
C:\Users\abhay\OneDrive\Desktop\scanner>`
how-to-fix-it?
@bot.hybrid_command() async def config(ctx):
can you send the full code? (make sure to remove your bot token)
i-fixed-it
sorry lol
ok
Could a while loop block other tasks from running? Should I consider using asyncio.wait_for() to set a timeout for a coroutine?
no unless if there is blocking code in it
Do you remember the most blocking code in bobux bot 💀
matplotlib?
Math command
Then how it doesn't work
If there's no reaction it's intents issue
Ok nvm it's not
Is that the whole code
ah right
@discord.ui.button(label="🔇", style=discord.ButtonStyle.grey)
async def mute(self, interaction: discord.Interaction, button: discord.ui.Button):
vc = discord.utils.get(client.voice_clients, guild=interaction.guild)
if not vc or not vc.is_playing():
return await interaction.response.send_message("There's no music paused now!")
else:
if vc.source.volume == 0.0:
vc.source = discord.PCMVolumeTransformer(vc.source, volume=50.0)
await interaction.response.send_message("Music unmuted")
else:
vc.source = discord.PCMVolumeTransformer(vc.source, volume=0.0)
await interaction.response.send_message("Music muted")```
How suppose i edit?
I mean the vc.sourse.volume it's getting error
the largest is 1.0 represents 100% btw
Oh
if you wanna set the volume, just set as attr, vc.source.volume = .5
I'm using buttons
Like add 5 each time
uh okay?
When it reach maximum it stop add and say a sentence
Then will it be the error?
The error is vc.sourse has no "volume"
whats your code
This
Or u need entire?
can you show the entire traceback?
i see
Where do you think it's error? : o
the error is you haven't transform it yet to PCMVolumeTransformer
I see
How suppose i transform into?
so maybe like, ```py
new_volume = 0.5
current_volume = getattr(vc.source, 'volume', None)
if current_volume is None:
vc.source = discord.PCMVolumeTransformer(vc.source, volume=new_volume)
elif current_volume == 0.0:
vc.source.volume = new_volume
else:
vc.source.volume = 0
honestly i dont see much info on it
excuse me haw can i install pygame?
well u have 2 separate definitions of MyClient classes
you need to combine the logic into a single on_message method with one class.
❤️
do u understand what argument it's asking for?
do u know what intents are?
take a look at the documentation and look.
What is a discord signing bot
Please check dm
One message removed from a suspended account.
One message removed from a suspended account.
line 18, youre not returning anything or youre not rlly doing anything there
call a function there i guess it should fix it
if statements need to have logic inside of them
One message removed from a suspended account.
Just remove the if statement if you aren't going to use it
One message removed from a suspended account.
Question, is there a way to add autocomplete to a slash command? like /buy 3000 (Autocomplete Good to purchase)
Is it possible to store a dictionary within a database? I need my bot to have the value of a dictionary stay the same even if it goes offline, but I’m not sure if it’s possible to do so.
You have no logic inside of it
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
One message removed from a suspended account.
Depends on which database you're using
Awesome thanks
Add logic inside of the if statement
One message removed from a suspended account.
What database should I use to accomplish this?
An if statement is the block of code that comes after “if”. It is required that you put some block or line of code after it.
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
How this bot showing exact expires time without editing msg again and again, ?
How can I create expiry like this ?
Oho, thx but is there any example code of it ?
You just send it
<t:1543392060>
Yes yes got it thanks you so much ❤️
Use JSON
JSON is not a database, should not be used as one
Is there an easy way to learn coding a bot
YouTube has multiple different ways it’s hard to learn on YouTube for me🫠
Youtube is a terrible resource for discord.py
There is not 1 good up to date tutorial
Creating ideas for features/commands is probably going to help point you in a direction, so it's what I'd recommend
Doesn't have to be anything complicated, you can just do simple messaging commands
Ok thank you 🙏
I will try in morning it’s 2am for me
How do you convert your message to a link? i thought only bots/webhooks could do this
[Text](URL)
Ive tried this.
it works, ig i formatted it wrong
Line 18, you have used an if statement but there isn't anything inside it so Python is expecting for there to be something there essentially but you haven't gave an 'argument' or in simpler terms what you want the code to do with the if block
is there a way to make bot discord online froever while computer is offline?
dont say vps im broke asf
I've heard they removed their free plan
I don't know whether you can host Python apps on it
Heroku is not for that i guess
Anyone help me with
My bot the shit ban command is not working
Look at this code
Cant ban a member from server what should i do🥶
Any error?
I wonder why there's a built-in ban button and a slash command
so cant we create a ban and kick command?
You Can but why if there is already built in
agree 100. they don't use commands rather they use on_message events most of the time
can bots read the timestamp of rich presence? using discord.Activity
Should be the created_at attribute for all activity types inheriting discord.BaseActivity
is discord.Activity different compared to discord.BaseActivity?
Yes
whats the difference?
so I should be using discord.BaseActivity instead of discord.Activity?
No, I mean you can access created_at with any type of activity
The "07:41 elapsed" is calculated from it
Or from attributes which refer to the created_at attribute
would https://discordpy.readthedocs.io/en/latest/api.html#discord.Game.start work as well?
I think discord.Activity.start would get the job done, I just need the timestamp
is that right?
Streaming, CustomActivity don't have a start attribute for example
what are CustomActivity?
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
I see, thank you. I think discord.Activity.start would work
It depends on what activity you're working with
I just need Rich Presence as of now
What is this about
i am making it so that if i do a command it will show my rich presence in json
it's more so that bot tutorials in general only really show how to do one specific task in one specific way rather than having the viewer think and write it themselves
and they are usually out dated a few months after getting made
anybody can help me?
what with
can I force sync a command so I can see my new parameters? this is annoying af that I have to wait 1 hour
u don't
its instant now
at most u would have to reload discord
hello
any tips on getting started to making bots ? i already know python tho
How can I make slash commands, i've tried so much and it's just not working
what lib are you using, and what have u tried?
https://fallendeity.github.io/discord.py-masterclass/ here u go has most of the basics down
A hands-on guide to Discord.py
looks gpt generated
u can just use discord.py for slash commands no third party module needed
@rigid bramble u can look here there is a slash command section under guide
thanks my g
return random.choice(Silly_List)```
list ``Silly_input2 = [":fire:", "bruh", ":hey:", "magnificent", "silly"]``
i want to make the bot respond with random.choice(Silly_List) if any of the inputs in Silly_list2 is typed, how would i do that?
if p_message in silly_input2
Are list comprehensions faster than loops?
# Separate users into "Ready" and "Not ready"
ready_users = []
not_ready_users = []
for member in voice_channel.members:
if member in users_queue_sorted:
ready_users.append(member)
else:
not_ready_users.append(member)
vs
# Separate users into "Ready" and "Not ready" using list comprehension
ready_users = [member for member in voice_channel.members if member in users_queue_sorted]
not_ready_users = [member for member in voice_channel.members if member not in users_queue_sorted]```
Which method should I use?
what 24/7 means
Here I'd prefer the statements version for the single looping
They should be about the same speed
You can just time it yourself
Which one would you personally use?
does anyone have an example on how to create groups and sub commands using discord.interaction and slash commands
for some reason my description is not appearing:
from typing import Mapping, Optional, List, Any
import discord
from discord.ext import commands
from discord.ext.commands import Cog, Command
class Help(commands.MinimalHelpCommand):
def __init__(self):
attributes = {
"name": "help",
"cooldown": commands.CooldownMapping.from_cooldown(2, 5.0, commands.BucketType.user),
"description": "This is a list of commands for RP Utilities"
}
super().__init__(command_attrs = attributes)
async def send_bot_help(self, mapping):
embed = discord.Embed(title="Help")
for cog, commands in mapping.items():
filtered = await self.filter_commands(commands, sort=True)
command_signature = [self.get_command_signature(c) for c in filtered]
if command_signature:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signature), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
async def send_command_help(self, command):
embed = discord.Embed(title=self.get_command_signature(command))
embed.add_field(name="Help", value=command.help)
alias = command.aliases
if alias:
embed.add_field(name="Aliases", value=", ".join(alias), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
async def send_error_message(self, error: str):
embed = discord.Embed(title="Error", description=error)
channel = self.get_destination()
await channel.send(embed=embed)
how do i learn python?
List comps
But list comp is faster always
They're using two list comps in the code, so that'll be two loops
So, I'd prefer the first one in this case
you wanna also consider readability
My bot's commands don't work for me but do work for another person... Whats the prob here?
Share your code
Sure
@final iron
The code might be a bit to disorganized. Pls don't tell me that since i already know lmao 😅
Hope you understand it tho
Oh didn't know, i was talking about in general

How do I add a new line to slash command value
I know this isn't exactly dc.py but can someone who still knows what reality is tell me what they have done with the active users list in the mobile app ??
What?
Can you give me an example?
The members tab in the search screen which shows when you click on the 🔍 icon on the top right corner of the chat screen
okay i see now... kind of annoying but i like the feel
And why is that? Because list comp should always be faster, even for this case no?
It is faster if you only need to loop once, but not when you're comparing two list comps to a single loop
why do u need two diff lists for that in first place
!timeit
a, b = [], []
for i in range(100):
if i % 2 == 0:
a.append(0)
else:
b.append(1)
@naive briar :white_check_mark: Your 3.12 timeit job has completed with return code 0.
20000 loops, best of 5: 10.4 usec per loop
!timeit
a = [0 for i in range(100) if i % 2 == 0]
b = [0 for i in range(100) if i % 2 != 0]
@naive briar :white_check_mark: Your 3.12 timeit job has completed with return code 0.
20000 loops, best of 5: 14.6 usec per loop
A little slower
@mild tide ^ check this out
We were doing a bunch of tests yesterday
!timeit
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}
# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)
print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
@young dagger :white_check_mark: Your 3.12 timeit job has completed with return code 0.
50000 loops, best of 5: 7.64 usec per loop
After putting condition can i order list somehow?
If a 1+2
If b 5+6
If c 7+8
Now can i order program to print abc
@naive briar This one is winning with 7.64 and we are using list comp
Those are not list comprehensions
That's just initializing lists from sets
!e
print(list({0, 1, 2}))
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
[0, 1, 2]
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])
# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)
print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
Could you do that same thing with a list, or does it have to be a set?
this is the one using lists from last night
Because we are comparing two lists from each other
the other list is just negation so only one list is enough
Can you show me an example?
We need ready_users and not_ready_users
how exactly are u using them?
We want to show both lists
voice_presence = {member: member in users_queue_sorted for member in voice_channel.members}
why not something like this?
What are you fellas trying to do
Beerhunter is in the room and wearing a blue shirt
Asher is in the room and not wearing a blue shirt
just create 2 batches from users who are in a voice channel and those who are not
Checking users in a voice channel and in the queue versus those who are not in the queue but still in the voice channel
So ready_members and unqueued_members?
total_connected_members = set(voice_channel.members)
queued_members = set(queued_member_whatever)
ready_members = total_connected_members & queued_members
unqueued_members = total_connected_members - queued_members # or total_connected_members - ready_members, whichever floats your boat
That is exactly what we did yesterday
How is it the problem of today
# Separate users into "Ready" and "Not ready" ready_users = list(users_queue_set & voice_channel_set) not_ready_users = list(voice_channel_set - users_queue_set)
Or is it not
Mostly me. I was just curious about what method to use if it's not a set
Looping and filtering
So something like:
for member in voice_channel.members:
if member in users_queue_sorted:
ready_users.append(member)
else:
not_ready_users.append(member)```
Yes
I get raise TypeError("cogs must derive from Cog") but i dont see anything wrong with the code
other cog is working
seems like you tried to load a cog that doesn't inherit from the Cog class
you'll have to post code and full traceback
Im getting errors when i import these two things:from discord.ext import commands,tasks
from discord import FFmpegPCMAudio
any mastermind able to extract the three dot animation from discord when an interaction is created and it says "thinking..."? I'd like to use it as an emote to indicate that the bot is typing gradually
i dont think this was answered yet but its possible you have an on_message event in your code somewhere that's messing with all your commands, in which case just change it to a listener
guys why my buttons are not getting enabled or disabled? i guess i did a dumb mistake
https://paste.pythondiscord.com/T5U3PV6GOVICHQATRYEPAMOC7Y
can I have buttons on a normal message which is not an interaction?
can someone make me a discord bot
Yes that was the problem i fixed it
Now my bot is ready i added many commands working perfect
Does anybody know how to reference the discord bot in a cog i want to check if bot it in a voice channel in a slash command
self.bot
for checking the bot's voice in particular, you'd want the guild object which contains the bot's voice client when they're connected
!d discord.Interaction.guild
property guild```
The guild the interaction was sent from.
!d discord.Guild.voice_client
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol) associated with this guild, if any.
what id?
like returning a previously received Interaction object by id? sure i guess, you can use a dictionary and on_interaction() to keep track of them, but it seems odd to need this
if you mean creating an Interaction object from an ID, it would require the original payload received from the gateway to reconstruct it
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/interactions.py#L167
discord/interactions.py line 167
def __init__(self, *, data: InteractionPayload, state: ConnectionState[ClientT]):```
wouldnt there already be some interaction store internally?
well i didnt see any in docs, and the library doesn't need one for anything afaik
hmm i see
I find it odd that there is no dpy feature for it, ill look into the reconstruction
So you would suggest me to create my own 'interceptor' to also receive interaction object payload and make this payload encodable
encodable for storing it in my db
why do you want to recreate interactions from IDs? they only last 15 minutes anyway
right.. forgot about that
since i have a big sequence class that is orm and stage based
with a recovery system in case of outage
hence why i wanted to store an interaction, as i use this interaction object and its attributes multiple times throughout the sequence
ill just create an interaction dictionairy and store its attributes in there
and refractor my code
@staticmethod
async def map_varToInstance(guild: discord.Guild, var_name, map_var: Any) -> Any:
if map_var[0]:
if e := Config.VAR_TO_INSTANCE.get(map_var[1]):
instance = await getattr(guild, e)()
return instance.id
return map_var[0]
a little bit of context
@staticmethod
def mapInstance(instance: object):
instance_vars = dict(vars(instance))
for k, v in instance_vars.items():
if hasattr(v, 'id'):
instance_vars[k] = [v.id, str(type(v))]
elif not isinstance(v, (int, str, float, list, tuple, dict, set)):
try:
instance_vars[k] = [list(v), str(type(v))]
except:
instance_vars[k] = [None, str(type(v))]
return instance_vars
part of my orm thing
Hi guys, im trying to make a /say command kinda like in minecraft, but i just can't get it to work (im very new to coding)
main.py :
if __name__ == "__main__":
bot.run_discord_bot()```
bot.py :
```import discord
import responses
from discord import app_commands, Intents, Client, Interaction
cats = ["", ""]
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
bot_token = ""
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"{client.user} Online")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content in cats:
await message.add_reaction(":Cat:")
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f'{username} said: "{user_message}" ({channel}')
if user_message[0] == "<":
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
@client.tree.command()
async def hello(interaction: Interaction):
await interaction.response.send_message("Test")
@bot.tree.command(name="test", description="Test description")
async def add(interaction: discord.Interaction, word: str):
embed = discord.Embed(title="Here is it!:", description=word, color=0x9208ea)
await interaction.response.send_message(embed=embed)
client.run(bot_token)
I have of course removed my discord bot token but it would be inside the "" of bot_token = ""
Only functionaly it has right now is reacting to this cat emoji (inside joke with some friends of mine)
Currently the bot works fine with everything except the /say command (currently just called "test" i think) im not good at coding (yet)
Where are you syncing the command? Also what i is_private?
if the message is a dm
wydm where am i syncing the commad? like the server or?
The app commands, otherwise they aren't visible with /
might be
how would i do that?
i am very new to discord bots
then i would suggest reading the documentation first before jumping into it.
i tried to find some but none of it works, atleast when i try it
Okay, let me ask you something.
yes?
What do u think is wrong with your example? let's start there.
there are various examples in the official repository, and the documentation has a pretty good API reference, but it lacks a proper tutorial especially for their newer features like slash commands
fyi the send_message() / run_discord_bot() code isn't really a useful structure to follow, despite the number of bots you'll find on github using it
the code for your help command doesn't seem to add any description in the first place...?
i was placing it in init though
in __init__
you overwrote send_bot_help though, so you have to format the description into the embed yourself
that im missing something
the basic principles for setting up a slash command with d.py is to:
- define a CommandTree instance
- add your command to that CommandTree
- synchronize your commands to discord so your users can see them (the step that you're missing)
the simplest option is to sync your commands during startup, for example: ```py
from discord.ext import commands
bot = commands.Bot(intents=...)
commands.Bot comes with a CommandTree for free:
@bot.tree.command()
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("Hello world!")
Use setup_hook() to run something after your bot logs into discord:
@bot.event
async def setup_hook():
await bot.tree.sync()
bot.run(...)```
oh thank you so much
fwiw syncing your slash commands every restart is usually unnecessary and discord can ratelimit your bot if you sync too often, but you don't have to worry about it right now, later you can write an owner-only command to sync your commands when you need to
i'll keep that in mind, but right now im getting this error
yeah, the prefix is used for message commands
intents are define here btw, dunno if that would help
dunno why its still a required argument but you can just give it some random prefix like $ or whatever
so how would i add a prefix to it?
as per the error, command_prefix is the name of the argument so you would write command_prefix="some prefix here" inside Bot()
btw you also mis-capitalized Intents=intents
ah
^ i suggest starting from scratch and just writing out what you need to define your slash commands
completely start from scratch or?
YAY
sure, make another file if you want
I've tried to make more files for other stuff but it never worked, like the reactions thing it only worked when i put it in the bot.py file
the other code is getting in the way given that the slash commands were mistakenly over-indented
pycharm lets you define run configurations that only run one specific file, so you'll need to either change the run configuration, add a new one, or (arguably more simply) open up the built-in terminal and type out the file you want to run instead
sorry i didn't provide much information i was multitasking with the kids 🙂
no worries dude
a new run config? like the ```import bot
if name == "main":
bot.run_discord_bot()```
or the def run_discord_bot(): etc
its a pycharm-specific thing
https://www.jetbrains.com/help/pycharm/run-debug-configuration.html
ValueError: anchor not supported for multiline text
this doesn't look related to discord bots, but can you show the full error message?
???
no lol
list comprehension is like 40% faster or something
theyre not the same speed
Sorting through a list with 10000 elements, either 1 or 2
List comp: 3.3597519397735596
Regular for loop: 3.5107860565185547
Even with 10000 elements its a difference of 16ms
With only 250 elements the difference will be extremely small
what unit is that in? if its seconds, the difference is 151ms, but i assume the code was repeated ~5000 times so the actual performance per iteration would be even smaller
here's my benchmark measuring time per iteration https://paste.pythondiscord.com/Y2RQ py List comprehension: 395.60us For loop: 297.20us in context of asyncio/bot development, i doubt the performance of an occasional, sub-millisecond loop matters (unless it's super expensive to check member in users_queue_sorted, but we can't tell that from the original code)
How can i do this but with stickers
Currently it's looking for only
but i want it to also look for a sticker and add the same reaction
a sticker isnt a reaction
i want to add a reaction to a specific sticker
message.stickers
could you explain a bit more? im very new to coding, especially discord bots
I do know a bit about coding, just not discord.py
but for your specific thing
message.stickers returns a list
just do like
if your_sticker in message.stickers:
await message.add_reaction(your_emojithing)
print(message.stickers) worked to get id
thank you dude!
@unreal pilot@final iron@hushed galleon Sorry for the ping. According to this test, the loop is faster
^ measured ~8 microsecond difference here too
either way i would hope you don't need that level of micro-optimization, especially within a discord bot
Fastest script was created by @mild tide last night. Many users from the community were involved and discussed the matter.
#voice-chat-text-0 message
oh yeah set intersection perfectly represents the problem
@young dagger :white_check_mark: Your 3.12 timeit job has completed with return code 0.
50000 loops, best of 5: 7.46 usec per loop
Thats not a fair comparison tho imo
How would you have done it?
A for loop for each list instead of one for both
pogo
As you use 2 list comprehensions as well
can you help me for a min?
its less than a min
IndentationError: expected an indented block after 'while' statement on line 1
while n > 0: print (n)
... n = n - 1
File "<stdin>", line 2
n = n - 1
^
SyntaxError: invalid syntax
im new to this
and was lost in the tutorial thing
Show ur code
um okay
Also the error already says whats wrong
while n>0: print (n) n=n-1 print ('blastoff!')
yes but the dude in the video
can u open dms?
i cant send image here
I dont accept dm’s
ohh okay ill upload image eq
Why would you do that?
This has no indentation
Indentation matters
whats indentation
Because you also use two list comprehensions?
In a production environment you wouldnt, but to show for loop vs list comprehension its not a good comparison
alright I appreciate the help
i cant help u much
When u dont know what indentation is
Thats like the first thing of python
alright thanks for the advice
Its important in python
you see how the code is pushed to the right, that's an indentation
ohh alright thanks once again
Np! Goodnight
Can be a space, can be 2 spaces, can be a tab (best option)
how would i write this in command promt?
We don't have to do that with a for loop
how to fix it?
@bot.command()
@commands.is_owner()
async def reload(ctx, extention): # .load eco
bot.reload_extension(f"cogs.{extension}")
what's the full traceback?
Look at your spelling
thanks, I don't know English very well
https://paste.pythondiscord.com/CQCA
My bot's commands don't work for me but do work for another person... Whats the prob here?
I'm posting this again since no one replied earlier
Weird
Create a barebones implementation and start debugging
Whats a barebones implementation?
Implementation with only what's required
How do I make my code send a message to discord and what channel is needed? When I try to channel.send() It says something like this:
Traceback (most recent call last):
File "/home/runner/NoaKushiRewrite/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/runner/NoaKushiRewrite/main.py", line 56, in on_ready
await check_changes()
File "/home/runner/NoaKushiRewrite/.pythonlibs/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 368, in __call__
return await self.coro(*args, **kwargs)
File "/home/runner/NoaKushiRewrite/main.py", line 112, in check_changes
await channel.send(f'[{key}] Changed from {previous_val} to {current_val}')
AttributeError: 'str' object has no attribute 'send'```
Show your code
line 20 did you set it as str?
nope its an integer
error says its an str
wait i actually changed some stuff
now it says this when line 20 is an integer
Traceback (most recent call last):
File "/home/runner/NoaKushiRewrite/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/runner/NoaKushiRewrite/main.py", line 56, in on_ready
await check_changes()
File "/home/runner/NoaKushiRewrite/.pythonlibs/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 368, in __call__
return await self.coro(*args, **kwargs)
File "/home/runner/NoaKushiRewrite/main.py", line 111, in check_changes
await channel.send(f'{target_id} [{key}] Changed from {previous_val} to {current_val}')
AttributeError: 'int' object has no attribute 'send'```
yea you need to set the channel object first with bot.get_channel
this makes channel into None for some reason
so it also doesn't work
that needs to be set after the bot ready event is fired, which means it finishes filling cache, if it returns none, either cache isnt filled yet or id is wrong
same error
im sure the id is correct because i copy pastied it
show current code please

you're essentially doing this ```py
channel = 123
def function():
channel = 456
function2()
def function2():
global channel
print(channel)
function()
when you set `channel` in a function, it defines it at a local var, you need to reference the var `global` first to override it
!e ```py
channel = 123
def function():
channel = 456
function2()
def function2():
global channel
print(channel)
function()
@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.
123
also, that is not how you use a task loop, do check_changes.start() instead
this took a while but i get it now
lesson learned, thanks
also if i may ask for more help, the check_changes doesn't seem to be working properly, it just prints out both line 113 and line 115
something like this
i probably screwed up line 110 and line 111 :/
Dont use globals 🙏🙏🙏🙏
Just use classes pls
tell them that, i'm not gonna go through another topic to teach
Why not?
its hard to track and manage state and scope using globals which often cause bugs
^^^
Should I keep this format?
has more potential
make the banner color based on the rank that the person has
maybe try to shove in some emojis somewhere :d
well i have created this ticket system which has modals and buttons and store data in json file and 2 commands are not working.
the first:
the take category command which supposed to take the category id and later open in that category a channel. but the command doesnt even sync so i think its a typo that i havent got
the second:
my launch ticket system command dont work, take a stored data for embed description(the store data for the description worked) and have a button linked to the modal.
when i tried to launch it didnt work and didnt sent any error so i added try: and except Exception as e: and now it send me in return the server
code(changed the oriantation that the modal is on top then button then ticket class):
https://paste.pythondiscord.com/JJ7Q
the terminal:
https://paste.pythondiscord.com/3PAQ
the 2 last parts is from the except Exception as e....
if someone know pls tag me..
Well I know but I don't really wanna browse that whole code trying to figure out what exactly is wrong. Please narrow down the issue
Nobody is going to debug allat code for you. You need to debug it yourself, figure out which part is having the issue and if there’s an error
Then people would be more likely to help
guys why i see this when i close my bot?
await self.close()
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002246F2CB230>, 2411.437)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002246F201810>
Just run exit()
@app_commands.command(name="ticketscat", description="Set the tickets channel. enter the category name only!")
@commands.has_permissions(administrator=True)
@app_commands.describe(category="tickets categories")
async def ticketscat(self, interaction: discord.Interaction, category: str):
with open("cogs/json/tickets.json", "r") as f:
data = json.load(f)
data[str(interaction.guild.id)]["TicketCategory"] = str(category)
with open("cogs/json/tickets.json", "w") as f:
json.dump(data, f, indent=4)
ticketscat_embed = discord.Embed(title="Tickets category has been changed successfully!", description=f"The ticket category has been changed to: \n{category}", color = 0x020F81)
await interaction.response.send_message(embed=ticketscat_embed, ephemeral=True)```
idk why this command is not syncing while other commands are
How are you syncing it?
synced = len(await client.tree.sync())
print(f"CMD'S Synced: {synced}")```
other commands are syncing only this
i am not syncing command by command
it is like that for a few days and never took more than 3 seconds
3 seconds sound like per-guild sync.
If you sync per guild it will almost instantly sync.
ok i will switch to that and let you know in a few minutes
i am using the bot for multiple servers so i should do it for every server?
its dosnt sound right
No you should assign one development guild and then when you want to release it to others you should sync globally. This can be done neatly by using prod and dev builds
ok
the command is still not syncing
i want to restart bot, like closing and rerun it
fyi at some point global commands started syncing instantly, api docs didn't list this in their changelog but it's mentioned in the discord dev discord
@client.event
async def on_ready():
activity = discord.Game(name='Splatoon (In ' + str(len(client.guilds))+ ' servers)', type=1)
await client.change_presence(status=discord.Status.online, activity=activity)
print(f'{client.user} is online')
server_id = 1117262143159541792
channel_id = 1174376047735738368
server = client.get_guild(server_id)
channel = server.get_channel(channel_id)
if server and channel:
embed = discord.Embed(
title="I went online!",
description=f"{client.user} is successfully online!",
color=0xebd517
)
await channel.send(embed=embed)
try:
synced = await client.tree.sync()
print(f'Synced {len(synced)} Commands')
except Exception as e:
print(e)
scheduler.start()
async def send_invites(channel, server_id):
for guild in bot.guilds:
if guild.id == target_server_id:
try:
invite = await guild.text_channels[0].create_invite(max_age=86400)
await channel.send(f"Invite link for {guild.name}: {invite.url}")
except discord.Forbidden:
print(f"Bot doesn't have permission to create invites in {guild.name}")
except Exception as e:
print(f"An error occurred while creating an invite for {guild.name}: {e}")
async def daily_task():
channel = bot.get_channel(channel_id)
if channel:
await send_invites(channel, server_id)
scheduler = AsyncIOScheduler(timezone=pytz.timezone('Asia/Taipei'))
scheduler.add_job(daily_task, 'cron', hour=22, minute=0)
scheduler.start()```
Why "cannot access local variable 'scheduler' whrte it is not associated with a value?"
At py schedular.start
err you have a scheduler.start() line in the middle of your function, above where you defined the scheduler
i suggest using the d.py's built-in tasks extension for this though
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html for example: ```py
from discord.ext import tasks
@tasks.loop(time=datetime.time(hour=22, minute=0)) # 22:00 UTC
async def my_loop():
...
@bot.event
async def setup_hook():
my_loop.start()```
also usually you should avoid running code in on_ready() because it can trigger repeatedly if your bot disconnects from discord
Okay
let me try a bit
what about now?
@client.event
async def on_ready():
activity = discord.Game(name='Splatoon (In ' + str(len(client.guilds))+ ' servers)', type=1)
await client.change_presence(status=discord.Status.online, activity=activity)
print(f'{client.user} is online')
server_id = 1117262143159541792
channel_id = 1174376047735738368
server = client.get_guild(server_id)
channel = server.get_channel(channel_id)
if server and channel:
embed = discord.Embed(
title="I went online!",
description=f"{client.user} is successfully online!",
color=0xebd517
)
await channel.send(embed=embed)
try:
synced = await client.tree.sync()
print(f'Synced {len(synced)} Commands')
except Exception as e:
print(e)
my_loop.start()
async def send_invites(channel, server_id):
for guild in bot.guilds:
if guild.id == server_id:
try:
invite = await guild.text_channels[0].create_invite(max_age=86400) # Max age in seconds (24 hours)
await channel.send(f"Invite link for {guild.name}: {invite.url}")
except discord.Forbidden:
print(f"Bot doesn't have permission to create invites in {guild.name}")
except Exception as e:
print(f"An error occurred while creating an invite for {guild.name}: {e}")
@tasks.loop(hours=24)
async def my_loop():
channel = bot.get_channel(channel_id)
if channel:
await send_invites(channel, server_id)```
”cannot access local variable 'my_loop’ where it is not associated with a value”
Why is your my_loop defined inside on_ready
if a command were to be used with a channel id as an argument, how would i check to see if that id matches a channel in the guild it was used in?
Prefix command or slash?
slash
You can't parse a channel from other guild using slash channel selection to my knowledge
async def cmd(inter: Interaction, channel: TextChannel)```
"TextChannel" is not defined by pylance
am i missing a library?
ok
ty
so
would that mean in the command you select the actual channel?
not the id?
Yeah
awesome
nice
slash commands have improved a lot since i last used them (that was years ago tho lol)
Years ago there was ugly discord_slash lib and it was very ugly indeed
yeah, i kinda tried it out and never used it again
Thx god disnake appeared
lol
I have this codemport discord
from discord.ext import commands
from discord import Interaction
from yt_dlp import YoutubeDL
from discord import FFmpegPCMAudio
import asyncio
class music(commands.Cog):
def init(self, bot):
self.bot = bot
self.is_playing = False
self.is_paused = False
self.music_queue = []
self.YDL_Options = {"format": "bestaudio", "noplaylist": "True"}
self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 - reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn'}
self.vc = None
and keep getting this issue [NULL @ 0000023902c35640] Unable to find a suitable output format for 'pipe:'
pipe:: Invalid argument
is it possible to change that if mode add is slected input is required:
@app_commands.describe(channel="Select a Channel")
@app_commands.describe(category="Select a Category")
async def staff_channels(
interaction: discord.Interaction,
mode: discord.app_commands.Choice[str],
input: discord.TextChannel = None,
):
so it only shows up if it is selected
@bot.tree.command(name="addchannel", description="Adds a channel to the list.")
@app_commands.describe(channel = "A discord channel")
async def addchannel(interaction: discord.Interaction, channel: discord.TextChannel):
with open('channels.json', 'r') as file:
data = json.load(file)
if not channel.id in data:
with open(channels.json, 'w') as file:
json.dump(channel.id, file)
interaction.response.send_message("Done")
im confused, im wanting to check if a channel id is in channels.json and if it isnt in it then it will add the id of "channel" to the file. the command doesnt respond and it gives me an error saying 'list' object has no attribute 'json'
"channels.json"
ur second with open has channels.json
yes
also u shouldnt use json as a db
its just a simple list of channels, i know that json isnt great but i havent coded in years so im not gonna jump right into sqlite yet
i will soon but im not ready for it atm
hey guys, i have a python bot that also uses selenium to webscrape, but i now have no idea how i can host it, as most hosting things probably wont support it. Anyone have any ideas? i dont want to host it locally
not sqlite either thats synchronous u need an asynchronous storage facility
such as
aiosqlite asyncpg aiomysql (sql flavors), motor (mongodb), aioredis (redis)
u need a vm or u can also do it without a vm using headless option for selenium
any host is fine ig
wdym headless option
headless dosent open the browser gui when scraping
im kinda not that advanced with it
ohhhh
u have an example?
lemme look at the docs been some time since i have played with selenium iirc there is a class called ChromeOptions
cool ty
options = ChromeOptions()
options.headless = True
driver = webdriver.Chrome(options=options)
driver.get('http://selenium.dev')
driver.quit()
also fyi this channel is for discord bots not (bots in general) afaik so next time probably use the #1035199133436354600
yeah its just that it is a discord bot so i thought that might be why
but ty, lemme try it
wait where do i define chrome options
wait i got it dw, ty
embed.set_thumbnail(url=interction.guild.display_avatar.url)
how to specify server avatar in embed?
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
i use disnake
Oh fr..? Why
iunno, but at least it's not going to trip people over anymore
Seems like they just wanted to test if it was plausable.
the earliest mention i found in their server was #697489244649816084 message which is over a year ago, so i don't really think it counts as a test anymore
still worth syncing to a guild if you don't want to show off your commands to the public, or if you think you might hit the 200/day ratelimit for command creations which is kinda tough to do by accident
Thanks for the search
I'm trying to implement hashlib into a bot to hash large sums of data
In hashlib's documentation I can see that
To allow multithreading, the Python GIL is released...
How can I take advantage of that with asyncio?
Is the asyncio.to_thread method what I'm looking for?
hasn't been yet its still in work and features are largely experimental and still limited to c api for now
it looks like that functionality has existed since at least python 2.7
If it doesn't matter whether I take advantage of the GIL release or not, can I use a ProcessPoolExecutor instead? Will a ProcessPoolExecutor work with asyncio?
is hashlib blocking?
afaik, yeah
then u need to use run_in_executor along with that
ah reading more of the asyncio docs,
Note
Due to the GIL, asyncio.to_thread() can typically only be used to make IO-bound functions non-blocking. However, for extension modules that release the GIL or alternative Python implementations that don’t have one, asyncio.to_thread() can also be used for CPU-bound functions.
So the answer is maybe, but then I'm still limited to single-core
u need run_in_executor it's a method for bot.loop object it runs the blocking code in another thread
is that different than the asyncio run_in_executor?
class GeneratorView(discord.ui.View):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.stopped: bool = False
@discord.ui.button(label="Stop", style=discord.ButtonStyle.red)
async def stop_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
self.stopped = True
self.stop()
message = await interaction.original_response()
await message.edit(view=GeneratorView())
async with message.channel.typing():
async for content in generator:
if view.stopped:
break
else:
...
any way to do this?
no its the same
have a stop button in a view to stop a generator from generating response
you can make the GeneratorView edit itself if that helps
just use the stopped attribute of the view?
a better or cleaner way might be to edit the wait method in the view
yeah, given that it releases the GIL, hashlib should run in parallel if you use asyncio.to_thread() or the lower-level loop.run_in_executor(None, ...)
wym edit method
!d discord.ui.View.wait
await wait()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.stop) is called or it times out.
tbh u can probably just use a while loop with the stopped attribute of the view
it doesnt work, the generator just runs until end
cool, thanks
would it be worth it to try to implement a ProcessPoolExecutor anyways in order to make things multi-core? theoretically the bot will need to be processing multiple hashes at once

