#discord-bots
1 messages · Page 328 of 1
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
is the bottom snippet exactly what you're using? if so, you haven't assigned view to the GeneratorView() instance you created inside message.edit()
^^
oh yeah no i just cleaned it up a bit
hold up
@app_commands.command(name="chat", description="Chat with the bot")
@app_commands.describe(prompt="The prompt to send to the bot")
async def chat(self, interaction: discord.Interaction, prompt: str, stream: bool = True) -> None:
await interaction.response.defer()
last_edit = config.misc.message_edit_interval
message = await interaction.original_response()
async with message.channel.typing():
payload = self.bot.openai_service.create_chat_completion_payload(prompt=prompt, stream=stream)
generator = self.bot.openai_service.create_chat_completion(payload=payload)
view = GeneratorView(bot=self.bot)
async for content in generator:
if view.stopped:
break
if time() - last_edit > config.misc.message_edit_interval and len(content) < Utils.MAX_CHARACTERS:
await message.edit(content=content, view=view)
last_edit = time()
u create the view but u never edited the message with the view here
crap yeah sorry I dont have it added since it didnt work
but i mean when I added it it still doesnt do it so yea
!d discord.Interaction.edit_original_response also u can use this instead of fetching the message and editing again
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) 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.
I need the original message for other purposes
like?
I have a thread feature so I need message ids and contents
doesnt really concern this feature tho
are you sure the stop button is actually setting the value to True
might wanna debug that
class GeneratorView(discord.ui.View):
def __init__(self, bot: MyBot, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.bot: MyBot = bot
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()
yeah
nothing wrong with the logic behind breaking out #bot-commands message the error is somewhere else
ur not responding to the interaction here do u not get a interaction failed response?
all interactions need a response
well setting the property doesnt take a long time, why would it matter
since I just check the property elsewhere
in case of components u can defer then indefinitely but for slash commands is compulsory to respond
did u log out the stopped property?
no not yet
question, I have a bot that reads csv files to read and write information, but I am moving the bot to bigger server with more interactions that could be simultaneous, is it better to convert this to sqlite for performance or does anyone have any alternative recommendations
sqlite would definitely give you better data integrity plus the capabilities of SQL, but see this conversation and the links for more info #databases message
a few messages below links to appropriate uses for sqlite
thanks, 2 follow up questions:
would I be losing performance for going sqllite instead of Postgres SQL?
what is the purpose of async support, am I just writting the code in a more familiar way with the rapptz asqlite? I mean I use it in discord py but Im self taught so I dont actually understand the purpose of it
for performance, it depends on how much traffic you're expecting to have but sqlite can be quite efficient in low-concurrency workloads
with asyncio, your program's thread needs to run an event loop constantly, but non-async libraries that take too much time to do something prevents your event loop from doing anything else, like responding to commands or keeping the bot's connection to discord alive
sqlite3 in particular will block the event loop if it has to do a performance-intensive query or wait for another connection to release a database lock
why are my discord images not loading in?
for example this ^
i have this little goofy image that i wanna load in, but its not showing up
any imgur gif that ive uploaded thus far is not showing up
I haven't been keeping up with sqlite for years, but has it ever become more than just an abstraction over simple text files? I don't know, why you'd ever want to use sqlite other than for prototyping or embedded applications. If you want to deploy an actual service, people are actually going to use, don't use sqlite
You only have that for embedded applications, so I guess what the colleague is saying makes sense
sqlite uses a binary format, is serverless (pro/con), and has all the benefits of SQL and ACID transactions without needing to read/write the entire file as one might do for simplicity
You're basically describing in-memory dictionaries with simple locking mechanisms
This is like saying a "programming language is turing complete" it doesn't give you much information
Hi guys, I want to get back working on a discord bot of mine which I stopped developing back when discord.py's developers announced it was ending, but I dont know if I should update my bot to discord.py 2 or nextcord. Can someone advice me which is the best option?
err sqlite isn't in-memory, and SQL isn't a key-value store - if you want that, you'd be looking at tinydb
btw this discussion should continue in #databases
I didn't say"SQL is a key-value store." I've just pointed out, that your comment doesn't contribute much to the discussion
discord.py i believe still remains as the most popular library for discord bots, so you're more likely to find people that can help you with it
ty
What does this error mean in discord Dev?
I read the full error too, still didn't really understand?
a react error lmaoo
You know how you have this for discord.py? I currently know how to add parameters and everything to it, but I have one question. I have a list of string's that I want to make the options for a parameter, if that makes sense. How would I do that? Like paramName: listName ??
fyi application commands don't take ctx as their first parameter, they take interaction and it's an important distinction
!d discord.app_commands.choices You can use this
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
Thanks!
@feral timber see how the gif command says Search for a GIF, my command just has "..."
I want to add a description above like the gif command.
Can you not just inline your description?
https://github.com/vipyrsec/bot/blob/main/src/bot/exts/dragonfly/dragonfly.py#L248
src/bot/exts/dragonfly/dragonfly.py line 248
@discord.app_commands.command(name="lookup", description="Scans a package")```
I think they're after descriptions for each parameter, not the command itself
Yup
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
How do I add subcommands with discord interaction?
Like if I want to have /alliance create
/alliance add
/alliance kick
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
preitiate it
just add another argument to the command after Interaction
i.e ```somegroup = app_commands.Group(name="mycommandgroup", description="some commands but grouped")
@somegroup.command(name="ping:, description="ping the bot")
async def ping_slash_command(self, Interaction: discord Interaction, somearg: str):
if somearg == "subcommand"
try:
subcommandstuff
except Exception as e:
print('something broke')
elif somearg == "subcommand2"
try:
somethingelse
just one way to do it
This isn't so "Discord bots" stuff
What
You should be creating sub commands properly
u can use groupcogs for making subcommands
I have two slash commands both interactive. But one gets registered and I am able to interact with it and the other doesnt, any idea ?
import discord
from discord.ext import commands
from discord import app_commands
import logging
from colorama import Fore
import random
bot = commands.Bot(command_prefix='!' , intents= discord.Intents.all())
handler = logging.FileHandler(filename='discordPY.log', encoding='utf-8', mode = 'w')
@bot.event
async def on_ready():
print(f'{bot.user} is ready to rumble!')
print('Published by Moritz Reiswaffel')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} commands!')
except Exception as e:
print(e)
print('------------------------------')
@bot.event
async def on_message(message):
print(Fore.YELLOW + f'In server: {message.guild}')
print(Fore.GREEN + f'Message from {message.author} in channel {message.channel}: {message.content}')
@bot.event
async def on_message_delete(message):
print(Fore.YELLOW + f'In server: {message.guild}')
print(Fore.RED + f'Message deleted from {message.author} in channel {message.channel}: {message.content}')
@bot.event
async def on_message_update(before, after):
print(Fore.YELLOW + f'In server: {before.guild}')
print(Fore.BLUE + f'**{before.author}** edited their message: \n BEFORE: {before.content} --> AFTER: {after.content}')
# Commands
@bot.tree.command(name='get_word')
@app_commands.describe(output = 'Wie soll der Code sein ? ')
async def pwd(interaction: discord.Interaction, output: str):
await interaction.response.send_message(f'Ok, **{interaction.user.name}** der Code für die test Rolle ist jetzt: `{output}`')
# Ich will den Output in eine Liste speicher, sodass der Bot später darauf zugreifen kann
Data = []
Data.append(output)
print(Data)
@bot.tree.command(name='test_role')
@app_commands.describe(input = 'Wie lautet der Code ?')
async def eingabe(interaction: discord.Interaction, input: str):
if input in Data:
await interaction.response.send_message(f'Ok,**{interaction.user.name}** du hast den richtigen Code eingegeben')
else:
await interaction.response.send_message(f'Ok,**{interaction.user.name}** du hast den falschen Code eingegeben')
bot.run('Token would be here' , log_handler=handler)
what does your on_ready function print for len(synced) commands?
Synced 2 commands!
Seems I took some time idk, just came back after a break and now its there.
prolly just reload discord next time
happened to me previously few times as well
Is there any way I could make this easier?
# Create a progress bar using custom emojis
if progress == 0:
progress_bar = '' + '' * 9
else:
filled_bars = int(progress * 10)
if filled_bars == 0:
progress_bar = '' + '' * 9
else:
progress_bar = '' * filled_bars + '' * (10 - filled_bars)
The idea is that the progress bar never should be completely empty
What is bar_mixed, bar_grey, and bar_blue?
print('Hello world!')
Syntax error: “print” undefined!
how can I prevent from being rate limited ?
Don't spam API requests...?
and dont use replit if ur using it
there's a third answer: destroy discord api and build a well working clone, your app, your choice
how does one get a discord bot to send a private message as a reply to a message?
!d discord.Message.author
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
if you want to create your own measurements against that: replicate a 'leaky bucket' sort of thing
where you regulate your requests
I don't believe so, no
ok
need ome help
Why i can’t run levels.py in cogs?
Why do you think you cant?
how do you properly make http requests?
can i make a discord bot communicate with a db ? and also how to make it attach a file ?
in discord.py since its async, use aiohttp lib for HTTP requests related
use a async database driver, such as asyncpg for postgresql
[you need to elaborate on attach a file part]
await send(file=discord.File(...))
!d discord.File
class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
How come I cant find any threads using this?
@tasks.loop(hours=1)
async def clear_threads(self):
async for guild in self.bot.fetch_guilds():
for thread in guild.threads:
if thread.owner == self.bot.user:
if time() - thread.created_at.timestamp() > config.misc.thread_lifetime_minutes * 60:
...
yeah but, is there a way to use the bots own sessio? or do i create my own session? if I create my own session, how do I get it shared across all commands?
if you're doing HTTP request outside of discord api you have to create your own session
see the notes there
guilds is empty though, fetch_guilds at least returns the guilds
do I have to fetch each guild after using fetch_guilds?
perhaps you were using it before ready event is called? If so, use bot.wait_until_ready before using that attr
!botvars
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
it's not documented but there's an http attribute on your bot object
but as said before you're best off creating your own session and stuff if what you're doing is outside the scope of the library
It's a progress bar that updates as the progress value changes
i have a python script that allows me to download files to a specified path
and i'd like to make my bot attach the said file
hmm ok
'attach said file'? to a message? pretty much just this #discord-bots message
use mongodb :0
mongo has an async driver 'Motor' very easy to use
so incase you dont know sql, use pymongo's 'Motor'
as a mongodb user, i do not get it
tbh its good to use sql db incase you have a reson to use no sql
With Discord.py can I pass my Embed object a dict for the fields.
I have this and was hoping I could do somehting like embed[fields] or somehting instead of looping through the dict doing add_field
embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)
fields = {
"field one name": "field one value",
"field two name": "field two value"
}
you can form an embed from dictionary but not with this style
it would have to be style that is set by discord
in this case what you have, you have to iterate over dict to add those fields
oh so I have to convert the entire embed to a dict.
hello i am trying to create a wordle game and i get a weird error:
'function' object has no attribute 'to_dict' ```
the cog:
```py
import discord, random, utils
from discord import app_commands
from discord.ext import commands
from utils import generate_puzzle_embed
class wordle(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(description="Play a nice game of wordle")
async def wordle(self, interaction: discord.Interaction):
embed = generate_puzzle_embed
try:
await interaction.response.send_message(embed=embed)
except Exception as e:
print(e)
async def setup(client):
await client.add_cog(wordle(client))```
the utils file:
```py
import discord
def generate_blanks():
return ":white_medium_square: :white_medium_square: :white_medium_square: :white_medium_square: :white_medium_square:"
def generate_puzzle_embed():
embed = discord.Embed(title="A game of wordle has been started")
embed.description = "\n".join([generate_blanks()] * 6)
embed.set_footer("To start a new game use the command: /wordle \nTo guess reply to the message")
return embed```
you need to call the function: generate_puzzle_embed()
added it but still
did it print an exception?
do you have an error handler (on_command_error, etc)
You don't need to, I'm just trying to figure out why you aren't seeing a traceback
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
that might be why
yep
thx, working now
Is the first block the correct list comprehension for the below block
fields = [embed.add_field(name=key, value=value) for key, value in fields]
for key, value in fields
embed.add_field(name=key, value=value)
This si the dict I'm working off of
embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)
fields = {
"field one name": "field one value",
"field two name": "field two value"
}
the second block isn't building a list though
embed.add_field doesn't return some useful value that you store in a list
fields would just be a list of None values in your list comprehension
Oh, I'd forgotten to add some context; this is what my field dict is. This is declared outside of the loop
embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)
fields = {
"field one name": "field one value",
"field two name": "field two value"
}
commands not working
code is not mine, someone gave me months ago, when he gave me code it was working perfect, commands working too good but then commands stop working (here is code link)
https://paste.pythondiscord.com/MNXA
I'd argue sqlite is much more well-suited to most discord bot projects, picking up SQL isn't too difficult
for what reason?
well, ig its serverless
but how does that make it better for discord bot projects
ayo , the bot concept is nice
a wordle bot
looks cool too 👍
I've used PyMongo and Motor-Asyncio and I feel that most bots lend themselves well to a relational-style database system, given that every discord object can be stored via it's unique ID. I also think that the Mongo Python drivers leave something to be desired in terms of documentation/type annotations. And they introduce an unnecessary dependency on mongoDBs services for the bot to function.
unless you have a specific need for storing stuff in mongo's JSON-style documents I'd usually just recommend just using SQL and an on-disk database
Thx
im not convinced by what youve said
you keep your explanation too abstract
in case of relational-style, that is what mongo uses as well
a document, as you know
no mongo is non-relational
ah yea youre right
tho a non relational style still doesnt mean its not suitable for filtering by ids
if i were to have a
object_id in my non relational db
Anyone got any thoughts on this list comprehension being valid
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
the list comp is fine but fields will just be reassigned to references of the same embed object
it has tasks.loop(hours = 1) decorator, how do I run it only after its ready
Do you mean it will start iterating the field's dict but then will start iterating over the fields list after a few runs?
Do I need the fields list array or can I remove it whilst still making the loop a one-liner?
!d discord.ext.tasks.Loop.before_loop
@before_loop```
A decorator that registers a coroutine to be called before the loop starts running.
This is useful if you want to wait for some bot state before the loop starts, such as [`discord.Client.wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready).
The coroutine must take no arguments (except `self` in a class context).
Changed in version 2.0: Calling [`stop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.stop) in this coroutine will stop the loop before the initial iteration is run.
ty
embed = discord.Embed(title="my title" ,description="some description" ,colour=0x1E90FF)
fields = {
"field one name": "field one value",
"field two name": "field two value"
}
for k, v in fields.items():
embed.add_field(name=k, value=v)
this is sufficient no need for any unecessary comps
Thanks Asher
can I delete multiple threads with 1 request?
also is there no way to create a thread from a message that is private? I'd like if it was possible to create threads for users so that it doesnt flood the channel thread list
No, this is to prevent mass deletion aka raids.
i feel threads have lost value since forum channels came out
That and it not automatically opening when clicked on the main channel
is this possible though?
wdym by message that is private?
i think you're simply looking for private threads, since those don't send a message to the channel when they get created
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.
New in version 2.0.
do private theads have a starter_message
apparently not
just send an embed with message jump link
starter_message is also None when a user creates a private thread, which is kind of weird because discord's UI requires you to send a "Starter Message"
but i guess starter_message only applies to threads created from an existing message, i.e. what the Start Thread from Message endpoint does
Too bad 😕 Would've been good for what I'm doing
why not create a private thread and send the first message in there instead?
Hmm maybe, I'd like if the prompt message was visible somewhere in the thread, technically possible with webhooks but would prolly look weird
not that the message is visible in public threads either, but it's in the original message
i guess your slash command could send a modal instead of a message to type out their prompt (which also lets you accept multi-line input), and then you can defer the modal interaction and create a private thread with the prompt and response in separate messages
oh multi-line input would be nice, I didnt know bots had modals, ig I could try that
!d discord.ui.Modal has an example
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...
What package should I use for doing voice macro commands?
What are voice macro commands
Pretty much just commands that execute when the bot hears a voice in a vc, I’ve seen it done before and it looks pretty cool, I’m just not sure where I should start with making something like that.
Or at least I think that is how the bots I’ve seen work, I’m not certain though.
Voice receive extension package for discord.py. Contribute to imayhaveborkedit/discord-ext-voice-recv development by creating an account on GitHub.
When it actually hears a voice, or when there’s any output from a user in a voice channel?
Output
I think you’ll still have to use this
I don’t believe discord returns is_talking or similar
hey, i'm trying to work on a project involving discordpy with others, if you are interested please dm me!!!
Hey I was wondering, is there any framework to develop discord bot text based games? I only found https://pypi.org/project/DiscordGame/ which doesn't seem developed anymore. I am now working on a bot game that's based on text commands and reactions, but it's becoming spaghetti code. If there isn't such a framework I was thinking about developing one..
can someone help me with my code? The kick command isnt working and I dont know why
the code on the right is the moderation file
add the setup function above the line bot.run and also call the function like so setup(bot)
lol no
The setup function needs to be in the same file as the cog
no not really
they aren't even loading the extensions
no wait
ok my bad
but that would work too
How can I pass client object to other files? It appears if I make client object global and use in another scope it says that I can't do that as loop is already running:
async def main():
logging.basicConfig(level=logging.INFO)
async with create_pool(
host=HOST,
port=PORT,
user=USER,
password=PASSWORD,
database=DATABASE_NAME,
) as pool:
async with TicketBot(
db=pool,
initial_extensions=load_cogs(),
command_prefix='!',
intents=discord.Intents.all()
) as client:
await create_db()
await client.start(token=bot_token)
used asyncio.run on this function
What "other files"?
I have utils.py where I need to pass guild object to a certain function, but without client/bot object it's kinda not possible
as I need to use bot.fetch_guild
Any chance you could send your code?
yea
:incoming_envelope: :ok_hand: applied timeout to @void mauve until <t:1702578352:f> (10 minutes) (reason: newlines spam - sent 105 newlines).
The <@&831776746206265384> have been alerted for review.
!unmute 399163302455803904
:incoming_envelope: :ok_hand: pardoned infraction timeout for @void mauve.
!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.
Please use paste services for longer code snippets
otherwise the bot will mistake you for a spammer
ok thanks\
sent you everything in dms tho
reactions and text usage has been minimized in favour of interactions and modals mostly
That works too, I’m just looking for a library or framework that would handle things like game state, serialization, dialogues and whatnot you might need for a game
well there isn't really anything extensive such as that for discord bots as a framework people just usually build their own based on games they want to make
what all features are u looking for as a framework
serialisation and game state i can see happening with some database adapter not sure about the others
Apart from managing the game state, things like translations, dialogue flows (do you know Disco Elysium? It was a dialogue heavy game, but implementing such thing is not easy), DnD style games, character customization so easy manipulation with mutable attributes, asset library and oh well I guess I'm looking for a game engine but instead of some vulkan/opengl/directx rendering, it will work with discord input (be it text, reaction, modals, it'd be up to the developer)
but yeah I am making my game and it feels like a chore reimplementing building blocks that could be done generic in some library
especially the dialogue flow, you need to keep the state of the dialogue and know what the user is replying to, then you get the branching and you don't want to see my code
tbf discord limits a lot of what a game possibly can be and at the end of the day interactions are just a few of them like a few button clicks or some text message or a select
so when making ur game u would be using these now when making a module with these its hard not to end up with a package of games instead of like a "game engine"
dialogue flow imo is mostly customisable to each use case and at the end these are just a bunch of callbacks atleast as far i use (interactions) which edits the view further
So in conclusion there wouldn't be much benefit to having something like that you think?
Are ephemeral embeds a thing?
Yes
Sweet. Thanks.
Anything thats sendable inside a message can be ephemeral.
Buttons. Modals and even custom formats like invite embeds etc.
Would be a nice update for the Python bot, an ephemeral help command with buttons :)
Currently doing an update to the voice verify thingy with a persistent button. I wouldn't mind working on (or having others work on) overhauling things to be more interactions based. Not 100% what the feeling is on that, though
imo hybrid commands or autocompletes for existing commands such as rules tags etc would be cool
We do have slash commands for the tag system
Yea especially hybrid since then the old option still persists.
Oh fair, I forgot about hybrid
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
for this? ^^
it would be cool to have it for the above as the other alternative is to go to the docs if u forgot the attributes
Would be interesting to see what people would use, message or slash commands.
I know for mod and admin stuff, it'd take a while for me to get used to using the slash commands
Been doing the regular commands for so long
Actually the discussion about the hybrid commands might be worth bringing up in #community-meta
Actually if a command doesn't take longer than 3 seconds it's nearly identical minus the decorator.
How much work do you have to do to convert?
Do you mean for the bot to finish executing the command?
@commands.command to @commands.hybrid_command
That's... much less work than I thought it would be
its pretty less
Depends on the cmd ofc but a simple command would only need a change in decorator. This is assuming there is no custom context being used.
if it takes longer than 3 secs discord stipulates u have to defer the interaction and then respond between 15 mins thats the only thing u need to take care of
I guess that makes sense
Yes for example the current message command for help depending if using raw_reaction_add or wait_for, wait_for would keep the command alive and thus timing out the slash command.
I think in our case most of that is managed through redis and scheduling
Yeah, they're setup as separate scheduled tasks and checked on
All that routes through here
What exactly is the benefit of this?
Consistent tracking and logging for anything we have to schedule
allows a lot more management of tasks unlike fire and forget here u can manage task states when to start, cancel, how many pending and so on
one simple example say u have bunch of tasks fired on startup for a specific task say caching but this task was cancelled or aborted u would want to clear up ur bg tasks as well to prevent resource wastage
Is there any free tournament bot?
There would be more work than that, but that would be one of the main changes
Try looking on GitHub or top.gg. This isn’t really a channel to find discord bots
Oh my bad sorry
yo guys, im trying to host a bot that uses selenium, but it seems like applications like replit wont work with it as obviously it cant really open an app in a online environment, does anyone have any solutions or free/cheap hosting they know will work with this kinda thing
See: #1184898165057527838
ight
Hello! I'm looking to see if anyone's up to chat with me about approach for a discord dnd bot. I'll be tracking sessions attended and points earned. This would be for folks who aren't tech savvy, so it has to be kind resilient to garbage
Feel free to ask a specific question if you have them
How do you safely do a database for this kind of application?
What would you consider unsafe?
Like most things in life a relational database will solve your problems 👍
Something that crashes if multiple people are using it, crashing if it handles ususal text (i know i can use placeholders in sqlite3 for that part) and poor error explainations
I am so bad with databases as much as I try, i'm still very new to them
Would you have a suggestion on making it not garbage?
boils down to good data modeling and normalization
How do you normalize data when you can't fully expect the inputs? Just a lot of solid error handling?
What do you mean, you don't expect the inputs? What exactly are you going to be storing?
... now that I think of it, I think i'm being paranoid in that respect 😅
I'm expecting odd naming schemes for player names (potential characters like undescores) and character names, and then numbers for the point counting
As long as it's valid UTF-8 most databases will be able to handle it
Happy to hear that!
if I have just a separate computer tower running the bot, do I need to worry about a formalized service?
You can either have your database from something like Amazon Web Services or Microsoft's Azure if you want redundancy, reliability, and security, but at the cost of price, or you can self-host a Postgres container or similar
I know zero about postgres, so I'll have to read into it
I may be worrying too hard about this project, haha
Do folks do code reviews in this server?
SQLite3 should work fine too. Just doesn't scale that well, if that's something you're worried about
We do code reviews, in fact there's a Code Reviews tag in #1035199133436354600 . Feel free to ping me over there whenever
I'll make sure I do that!
but for some reason it works on vs code
why shouldnt i print?
Why wouldn't it?
I mean I really dont know the answer to that
but can you explain on why I shouldnt be printing it?
Look at the expected input/output
How do I use cogs? Is there an example I can see?
Didcord
Thanks. Should I add error handling for each cog individually, or should I create a single cog to handle all the errors?
both
the single cog should be a fallback - like if the error was unexpected
otherwise you can just handle known cases in each cog themselves
You don't run the cog file, you run the main file
How to get list of the threads in a current channel? channel.threads seems to output nothing but an empty list
@tasks.loop(seconds=5)
async def auto_delete_task(self):
AUTODELETE_TIME_THRESHOLD = timedelta(seconds=10)
guild_id = await db.select_guild(session)
guild: discord.Guild = await self.bot.fetch_guild(guild_id)
channel_ids = await db.select_active_channels(session)
channels = [await guild.fetch_channel(channel_id) for channel_id in channel_ids]
for channel in channels:
print(channel.threads)
for thread in channel.threads:
last_message_id = thread.last_message_id
if last_message_id is not None:
last_message = await thread.fetch_message(last_message_id)
print(last_message.created_at)
tz = timezone('Europe/Moscow')
time_diff = datetime.now(tz) - last_message.created_at
if time_diff > AUTODELETE_TIME_THRESHOLD:
await thread.delete()
print(f'Deleted: {thread.name}') @tasks.loop(seconds=5)
I'm seeing online in tutorials that you can't use client and bot.commands at the same time, but how does the discord bot connect without the client giving it a token?
I believe it has to do with abstracting message commands and command handling that way rather than general Discord applications vs bot users if you know what I mean
The bot classes inherit from the client classes
see note
Well it gives me the desired channel object, it just doesn't retrieve threads
i guess it didnt really elaborate clearly, when you do fetch_guild it is not constructed with cache, so when you do guild.fetch_channel the channel object is constructed not from the cache, so it doesnt have threads filled
👍
how do you print only the contents of a message (using on_message event)
cus rn when i print the message it comes with a lot of other stuff and i want to only work with the message content
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
with discord.py? you either use the description= parameter, or add a docstring to your function
yes discord.py sorry
for example: ```py
@bot.tree.command(description="Do something fancy")
async def my_command(interaction):
...
or:
@bot.tree.command()
async def my_command(interaction):
"""Do something fancy"""``` the latter i usually find more convenient, especially when documenting parameters of that command since it supports numpy/google/sphinx-style docstrings, but the former is required if you intend to translate your bot using locale_str
so obv, thanks
hmm wait, auto_locale_strings= handles that so i guess technically docstrings are fine too
!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.
well, i ran into a problem in my wordle command. idk what is it tho. i only get "the application did not responde"
my cog code:
import discord, random, utils
from discord import app_commands
from discord.ext import commands
from utils import generate_blanks, generate_puzzle_embed, is_valid_word, random_puzzle_id, generate_color_word, update_embed
class wordle(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(description="Play a nice game of wordle")
async def wordle(self, interaction: discord.Interaction):
puzlle_id = random_puzzle_id()
embed = generate_puzzle_embed(puzlle_id)
await interaction.response.send_message(embed=embed)
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
ref = message.reffrence
if not ref or not isinstance(ref.resolved, discord.Message):
return
parent = ref.resolved #check if the message replies to the embed
if parent.author.id != self.client.user.id:
return
if not parent.embeds:
return
if not is_valid_word(message.content):
await message.reply("That is not a valid word!\nEnter a valid word of 5 letters in english only!", delete_after=5)
await message.delete(delay=5)
return
embed = parent.embeds[0]
embed = update_embed(embed, message.content)
await parent.edit(embed=embed)
try:
await message.delete()
except Exception:
pass
async def setup(client):
await client.add_cog(wordle(client))```
and this is my utils code where i have most of my functions:
https://paste.pythondiscord.com/44JA
i think it is some thing with the puzzle id
bc since i have added that it is not working
You have to respond to an interaction within 3 seconds
how do i start with python discord bots?
I am sry but what do you mean by that?
By what
Do you have a specific goal in mind?
id like to know what i can do first
You’re not being very specific. What can you do with what?
"You have to respond to an interaction by 3 seconds" what do you mean about the 3 seconds part
Are you asking how to respond to an interaction?
I know how to respond
But what do you mean bout by the 3 sec..?
I don't think I know what are you talking about
Seconds, as in the unit of time
OK, so my steps to fix it are to lower the message delay time? Or I am missing a something that I didn't understand
I think I don't understand what I need to do...
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...
This will give you 15 minutes to respond
I don't think you hot the problem bc I didn't explained it well....
When I am using the slash command(/wordle) I get an application command fail, since I added the puzzle ID function..
.
If its failing entirely that’s a separate issue, but its most likely just taking too long
Ohhh ok
it doesnt look like there's any blocking code in your util functions... did you get any error in your console? have you tried putting a print statement at the start of your command to see if it's being invoked correctly?
Console clear
I will try later
Thx for the help I am going to sleep I will update you later
Can someone please tell me why this cog isn't being shown as a /???:
import discord
from discord.ext import commands
from discord import app_commands
class Greetings(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
@app_commands.command(name = "hi")
async def hi(self, interaction: discord.Interaction, user: discord.Member):
await interaction.response.send_message(f"hi {user.name}")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Greetings(bot))
In main i'm using this lo load the cogs:
@bot.event
async def on_ready():
logging.info(f'Inicialidado como {bot.user}')
bot.tree.copy_global_to(guild = settings.GUILD_ID)
await bot.tree.sync(guild = settings.GUILD_ID)
for cog_file in settings.COG_DIR.glob("*.py"):
if cog_file != "__init__.py":
await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
You’re syncing the command tree, and then loading the cogs
Oh god, I'm dumb
Thanks
i am facing this error, and i have no idea why i am getting it
i am not even using audiloop library
remove the import
Guys can an Android phone be used for hosting a discord bot 24/7?
i am not even using it anywhere in my code
That's a warning not error
And it's being used by discord.py not by you
well right
You can ignore it
well i have to submit this project somewhere
not sure if submitting with warning in pytest file is okay
is there like a fix or something? that pytest ignores this warning?
The warning is just about depreciation like it will be deprecated in python , 3.13 which is in alpha yet ,
You can ignore it , I won't cause any error for now
I don't know how you can stop to show this warning, sorry
Used? Yes
Ideal? No
Why not ideal?
Guess it
import discord
ModuleNotFoundError: No module named 'discord'
how to fix it?
Use pip to install it , i recommend to install in an venv
thanks
yeah okay, thanks
its due to the operating system phones are based on which make development and dev related tools hard to operate on it they dont have the necessary binaries
i have added the defer, changed nothing maybe i am a dummy that dont know how to add this correctly
code:py @app_commands.command(description="Play a nice game of wordle") async def wordle(self, interaction: discord.Interaction): puzlle_id = random_puzzle_id() embed = generate_puzzle_embed(interaction.user, puzlle_id) await interaction.response.defer(ephemeral=True) try: await interaction.followup.send(embed=embed) except Exception as e: print(e)
and the terminal is still clear
@app_commands.command(description="Play a nice game of wordle")
async def wordle(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
puzlle_id = random_puzzle_id()
embed = generate_puzzle_embed(interaction.user, puzlle_id)
await interaction.edit_original_response(embed=embed)
try this
well, he is thinking in 15 min i will check
does it take that long to generate the puzzles?
are u sure the puzzle generation code is not raising any error that is going unchecked?
no it takes almost instantly without the random puzle id function in utils
that is the utils ^^^
tbh seems very likely it the puzzle generation function thats causing some error and that u dont have an error handler which causes the error to go unnoticed
def random_puzzle_id() -> int:
return random.randint(0, len(popular_words-1))
can u spot the issue?
len(popular_words-1)
i think i get it
also it seems u dont have an error handler which caused the error to go unnoticed i would recommend setting up one for future cases https://fallendeity.github.io/discord.py-masterclass/slash-commands/#error-handling-and-checks
A hands-on guide to Discord.py
the embed has been sent with the id thx
cool
i will check that out
u dont want errors like those to go unchecked makes it way harder to debug than it should be 😄
So how can I get necessary binaries?
I see many use termux and download Ubuntu or any light os in it
isn't termux an app
Ye an terminal emulator
iirc its a bit unstable on like Androids greater than 12 or smn
so you should be able to download it right?
I am on Android 9 (pie)
then it should be fine
Imma try
Is alpine os fine for running discord bot?
any os is fine you just need to be able to run a python process well prerequisite is python should be able to run and your phone cpu dosent arbitrarily clear up the process
can i make an error handler to events?
as in?
?
u need to register the error under the command tree if u want a global error handler
got it working the emoji codes are not good i will change it.
thx asher, pep
how do you check if a message contains attachments
and then send all the attachments that the message contains
!d discord.Messages.attachments - check if this is empty
No documentation found for the requested symbol.
!d discord.Message.attachments - check if this is empty
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Message objects, not the class
Yes?
ok lol i realized i never figured out how to check if a list is empty
how do you do this for embeds
await user.send(content=message.embeds[0].url)
didn't work
it says that it can't send an empty message
why is this an empty message and how do you fix it
what url are u trying to send
oh lol
!d discord.Embed.url can be string or None basically u cannot send None or empty string as a message
The URL of the embed. This can be set during initialisation.
await user.send(content=message.embeds[0].url or "No url present")
u would need to modify it like this
well its again about the wordle, i have this update embed function and i cant update the embed in the last part with the:py if guess == answer: if num_empty_slots == 0: embed.description += "\n\nPhew!" elif num_empty_slots == 1: embed.description += "\n\nGreat!" elif num_empty_slots == 2: embed.description += "\n\nSplendid!" elif num_empty_slots == 3: embed.description += "\n\nImpressive!" elif num_empty_slots == 4: embed.description += "\n\nMagnificent!" elif num_empty_slots == 5: embed.description += "\n\nWow buddy you killed it!"
that is the function:```py
def update_embed(embed: discord.Embed, guess: str) -> discord.Embed:
# Print the original description for debugging
print(f"Original description: {embed.description}")
puzzle_id = int(embed.footer.text.split()[16])
answer = popular_words[puzzle_id]
colored_word = generate_color_word(guess, answer)
empty_slot = generate_blanks()
embed.description = embed.description.replace(empty_slot, colored_word, 1)
print(f"Description after replacement: {embed.description}")
num_empty_slots = embed.description.count(empty_slot)
if guess == answer:
if num_empty_slots == 0:
embed.description += "\n\nPhew!"
elif num_empty_slots == 1:
embed.description += "\n\nGreat!"
elif num_empty_slots == 2:
embed.description += "\n\nSplendid!"
elif num_empty_slots == 3:
embed.description += "\n\nImpressive!"
elif num_empty_slots == 4:
embed.description += "\n\nMagnificent!"
elif num_empty_slots == 5:
embed.description += "\n\nWow buddy you killed it!"
# Print the final description for debugging
print(f"Final description: {embed.description}")
return embed
embed.description += ..... like this line what should i put instead?
can-u-show-code
use @bot.event
here:
@client.event(replace-here-instead-of-@client.event) async def on_message(message):
👍
Is there any way to simplify this code?
def generate_progress_bar(progress):
bar_25 = ""
bar_50 = ""
bar_75 = ""
bar_blue = ""
bar_grey = ""
bars = {
2.5: bar_25,
5: bar_50,
7.5: bar_75,
10: bar_blue
}
result = []
remaining = progress
for bar_value, bar_emoji in sorted(bars.items(), reverse=True):
while remaining >= bar_value and len(result) < 10:
result.append(bar_emoji)
remaining -= bar_value
while len(result) < 10:
result.append(bar_grey)
return ''.join(result)```
Working as it should, but it feels more complicated than it should
i mean it works 🤷♂️ seems readable too it aint that bad
Would you use list comprehension instead?
@commands.Cog.listener()
async def on_member_join(self, member):
key = f'wchannelid {str(member.guild.id)}'
key2 = f'wmessage {str(member.guild.id)}'
exis = await self.check_exists(key)
if exis:
channel1 = await self.bot.redis.get(key)
channel2 = int(channel1.decode("utf-8"))
channel = self.bot.get_channel(channel2) or await self.bot.fetch_channel(channel2)
message = await self.bot.redis.get(key2)
message1 = (message.decode("utf-8"))
key45 = f'embed {str(member.guild.id)}'
exis1 = await self.check_exists(key45)
if exis1:
embed = discord.Embed(title="", description=f"{message1.format(mention=member.mention)}")
await channel.send(content=member.mention, embed=embed)
else:
await channel.send(message1.format(mention=member.mention))
print(f"someone joined: {member.guild.id}")
```
2023-12-16 16:13:14 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag/cog-folder/join-leave.py", line 61, in on_member_join
channel2 = int(channel1.decode("utf-8"))
AttributeError: 'str' object has no attribute 'decode'
this is more suited for a #1035199133436354600 code review, but i'd probably use divmod instead ```py
def bar(progress: float) -> str:
progress = int(progress * 1000)
wholes, progress = divmod(progress, 100)
three_quarters, progress = divmod(progress, 75)
halves, progress = divmod(progress, 50)
quarters, progress = divmod(progress, 25)
empty = 10 - wholes - three_quarters - halves - quarters
return (
"4" * wholes
+ "3" * three_quarters
+ "2" * halves
+ "1" * quarters
+ "0" * empty
)
for progress in range(101):
print(bar(progress / 100), progress)```
apparently redis.get() already returned a string, so you don't have to decode it
does anyone know why i get this error
okj
Where would you define the emojis?
im decoding it to a int
i mean like you don't have to call .decode("utf-8") on it, decoding is only needed if you had a bytes object instead of a string
redis seems like an odd choice for this though
so how do io turn it to an int?
you just call int() on the string, nothing else
ok
thats the 4, 3, 2, 1, 0 in the code given above
u can hardcode it above
It's not working for some reason:
def generate_progress_bar(progress: float) -> str:
# Define your emojis here
emoji_whole = ""
emoji_three_quarters = ""
emoji_half = ""
emoji_quarter = ""
emoji_empty = ""
progress = int(progress)
print(progress)
wholes, progress = divmod(progress, 100)
three_quarters, progress = divmod(progress, 75)
halves, progress = divmod(progress, 50)
quarters, progress = divmod(progress, 25)
empty = 10 - wholes - three_quarters - halves - quarters
return (
emoji_whole * wholes
+ emoji_three_quarters * three_quarters
+ emoji_half * halves
+ emoji_quarter * quarters
+ emoji_empty * empty
)
@client.command(name='progress2')
async def progress2(ctx):
# Print progress bars from 0% to 100%
for progress in range(101):
print(progress)
progress_bar = generate_progress_bar(progress)
await ctx.send(f"{progress}%: \n{progress_bar}")```
u dont wanna send 101 messages 💀
(off-by-one)
i suggest testing your code in a console first
note that the unit scales in my example are different from your previous function
wait no including 0 its still 101 right?
It's printing out the correct numbers
They match, I mean
this one took a float from 0-1 and scaled it to 0-1000 before performing integer division
now im off-by-one :derp:
relatable ;-;
Gotcha. Thanks
How can I make a slash command option required?
they're all required by default unless you explicitly make it optional by typing it as Optional[T] or T | None
Assuming you're using discord.py, that is
I havent really used slash commands much, Can the options be stored in a variable?
guys i need help with my VPS
i can't acess my OVH cloud VPS even with my password
i tried acessing via root
but it's not aeessing even with password
i even tried without password and it's not acessing
discord.py accepts typehints for the options, so you'd need to make a typevar. but yes
i wouldnt define constant varriables in function but rather outside
You mean the emojis?
I guess
yeah but thats rather small improvement
i can look into the actual algorithm later
if that wasnt already optimized cause thats rather old message
Do you think this is overkill? 😅
Nah you are good 
what line of code would i write to ban people from there id
like !ban 991707603560300685
I mean it works
No, this is the type shit i like to see in a bot
attention to detail is great
have it overwrite rather than creating new image each time maybe? and randomize it so maybe go from 1 to 3 then 3 to 4, etc.
I was just testing the script
ahh
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
#client = commands.Bot(command_prefix=".")
__________________________________________
@client.command(pass_context=True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
await channel.connect()
print(channel)
Hey, guys its been a min this is old code to a cmd I was wondering what the change was to use the same old cmd but im just not sure how to set the prefix since the change?
Client doesn’t support commands, while Bot does
It has always been like this iirc
Where did you find this ancient code? 💀
lol thank you I knew it was a thing before but it was mine from a long time ago I was just wanting to update it to run again
Im finding my way but by chance do you know the change for
in on_message
await client.process_commands(message)
AttributeError: 'Client' object has no attribute 'process_commands'
Got moved to the Bot constructor.
You'd need to change to Bot or implement slash commands or find a different way all together.
Ah okay thank I appreciate it
is there no way to increase modal size? it's pretty small by default
if max characters is 4000 that's pretty small text area for it
nop frontend dev lazy issue, u can't rly change that
How can I convert the datetime for each user?
TypeError: can't compare offset-naive and offset-aware datetimes
it's basic
if you are using discord.py you need to use their method in discord.Member
Can't you compare utcnow with timedelta like this?
thirty_days_ago = discord.utils.utcnow() - datetime.timedelta(days=30)
if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:```
So in my database the timestamp is represent as: last_activity 2023-05-22T13:55:17.114+00:00
When I print out thirty_days_ago it's giving me 2023-11-17 10:34:09.434256+00:00
But then when I grab user['last_activity'] it gives me 2023-05-22 13:55:17.114000
And when I do the comparison if user.get('last_activity') and user['last_activity'] >= thirty_days_ago: it gives me:
TypeError: can't compare offset-naive and offset-aware datetimes
I'm so confused. Can somebody help me out?
Should I just do discord.utils.utcnow().replace(tzinfo=None) when I do the comparison?
I don't get it. Why is it showing +00:00 in mongodb
!d datetime.tzinfo
class datetime.tzinfo```
This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) to capture information about a particular time zone.
An instance of (a concrete subclass of) [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) can be passed to the constructors for [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) and [`time`](https://docs.python.org/3/library/datetime.html#datetime.time) objects. The latter objects view their attributes as being in local time, and the [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo) object supports methods revealing offset of local time from UTC, the name of the time zone, and DST offset, all relative to a date or time object passed to them.
And when I do print(user['last_activity']) it says 2023-05-22 13:55:17.114000
Btw ignore the date
I meant why is it not adding tzinfo by default as in the database
async def get_perspective_score(self, text, type):
# Specify the API endpoint URL and API key
url = 'https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze'
api_key = 'api_key'
# Define the parameters for the request
params = {
'key': api_key
}
# Define the request body
data = {
'comment': {'text': text},
'languages': ['en'],
'requestedAttributes': {type: {}}
}
# Send the request using aiohttp
async with aiohttp.ClientSession() as session:
async with session.post(url, params=params, json=data) as response:
result = await response.json()
return result
This keeps breaking
What about it is breaking?
like i think the request somethimes doesnt send
but it breaks somrtimes
Do you have a traceback
nope
It does look like its sending the request
I see the problem now
print("test")
content = content.lower().replace("niger", "a country").replace("ass", "arse").replace("phuck", "fuck")
modified_content = content
type = 'PROFANITY'
type2 = 'SEXUALLY_EXPLICIT'
result = await self.get_perspective_score(modified_content, type)
result = result.get('attributeScores', {}).get('PROFANITY', {}).get('summaryScore', {}).get('value', 0.0)
result2 = await self.get_perspective_score(modified_content, type2)
result2 = result2.get('attributeScores', {}).get('SEXUALLY_EXPLICIT', {}).get('summaryScore', {}).get('value', 0.0)
print("test2")
if result > 0.40 or result2 > 0.40:
if result > 0.40 or result2 > 0.40:
``` is not passing through
now its working
but for some reason
it stops working after
It doesn't seem discord-specific to me so consider opening a help post or something
I would really appreciate it if someone could explain this
Why am I getting a different value (without tzinfo) when I print it out?
It added tzinfo 00:00 which is eq to None, thats why you should always use timestamp
Python's datetime objects by default are naive, which means they don't have any timezone information IIRC
Documentation:
Aware and Naive Objects
Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.
The problem with timestamps is that if you host the bot over multiple servers or change to a different VPS in another location, the time zone will not be the same, and the comparison will fail. That's why I'm using discord.utils.utcnow
what're you trying to do @young dagger , i just woke up few mins ago 🥱
I want to use an accurate timestamp for future comparison
So the time will always be the same no matter where the bot is hosted
Uh
timestamp - 30 days will not be the same discord.utils.utcnow - 30 days if you change location, would it?
Just change it back
Because discord.utils.utcnow will always stay the same no matter where you are located
If I have multiple datetime objects with different timezones, I'd just convert them all to UTC before comparing them
Isn't that what I'm doing?
I don't even know your codebase, so I'm not sure
AFAIK discord.utils.utcnow just returns the current utc time
subtracting 30 days will give the same result regardless of the location, but a local timestamp will vary based on the timezone, so subtracting those 30 days could give different results in different locations, i would think.
Exactly. You took the words right out of my mouth
😆
I'm using discord.utils.utcnow() and here is the result in mongodb
Now when I do later comparison it doesn't include tzinfo
And for that reason I'm getting TypeError: can't compare offset-naive and offset-aware datetimes
How are you parsing it back into a date-time
users = await collection.find().to_list(length=None)
for user in users:
thirty_days_ago = discord.utils.utcnow() - datetime.timedelta(days=30)
if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:
### CODE HERE```
because one of your datetime object is aware meaning it has the tz information and the other comparison is naive meaning it doesn't have the information of the tz
we can't compare these two, it leads to issues like incorrect results.
you need to make sure they're both either aware or naive.
Yeah, I get that now. But still I'm wondering why user['last_activity'] is showing as aware when saved as naive in the database
ugh I'm not thoroughly familiar with mongodb here, sorry
because it always stores it in UTC and includes the information hence why it's aware in Mongo
so you need to convert it to a naive datetime in the same timezone.
So this would do the work. But is it the right approach?
thirty_days_ago = discord.utils.utcnow().replace(tzinfo=None) - datetime.timedelta(days=30)
if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:```
wouldnt if user.get('last_activity', -1) >= thirty_days_ago: do the work?
!e from datetime import datetime, timedelta; print(datetime.now() >= (datetime.now() - timedelta(days=1)))
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
True
yea ..
Yes thanks, it's either that or .replace(tzinfo=None)
The reason is that MongoDB is converting the timestamps to UTC and not including the offset on output
https://www.mongodb.com/docs/v4.4/tutorial/model-time-data/
voicec = message.author.voice.channel
await client.connect(voicec)
errors : Client.connect() takes 1 positional argument but 2 were given
Please send help
What are you trying to do
Connect the bot to a voice channel on command?
and I don't understand why it said that error...
Try this
voicec = message.author.voice.channel
if voicec:
if voicec.permissions_for(message.guild.me).connect and voicec.permissions_for(message.guild.me).speak:
voice_channel = await voicec.connect()
else:
await message.channel.send("No permissions.")
else:
await message.channel.send("You need to be in a voice channel for the bot to connect.")```
oh yeah, therefore I need the variable 🫡
Spoonfeeding isn’t helpful, and is generally discouraged
Yeah, I know how it feels when you want to get something to work. Sometimes it's just about the push in the right direction 🙂
That’s not a push in the right direction though. You gave him an entire block of code without explaining why his didn’t work, or what yours is doing
the error is saying you gave it 2 arguments but only expected one, which is a mismatch between how the connect method is called and how it's define in the library, which in this case the Client. Connect method doesn't take channel as a parameter, which is why Beer used Voicec.connect() and i believe you could also use VoiceChannel.connect() but not entirely sure.
whats the best server location for discord bots
There is none
I have two commands where you can make a "code" for a role, if a user enters the code with a slash command they get the role. You should be able to delete the codes but I cannot figure out how to check the whole file and delete the code the user input in the slash command
@bot.tree.command(name='delete')
@commands.has_permissions(administrator=True)
@app_commands.describe(input_one = 'Welchen Code willst du löschen ?')
async def delete_code(interaction: discord.Interaction, input_one: str):
if input_one in showCodes:
with open("codes.txt", "r") as file_input:
with open("codes.txt", "w") as output:
for line in file_input:
if line.strip("\n") != input_one:
output.write(line)
await interaction.response.send_message(f'Ok, **{interaction.user.name}** der Code `{input_one}` wurde gelöscht. \n Folgende Codes sind noch aktiv: `{DATA}`')
print(DATA)
print(f'Code {input_one} wurde gelöscht')
else:
await interaction.response.send_message(f'Blöd gelaufen, **{interaction.user.name}** der Code `{input_one}` existiert nicht')
print(f'Code {input_one} existiert nicht')
Why if my bot has administrator permissions and all the intents allowed, It can't auto-rol new bot using the on_member_join and neither send messages to specific channels though the on_member_join??
The Cog.listener looks like this:
@commands.Cog.listener()
async def on_member_join(self, member):
await self.setup_role()
await self.setup_bot_role()
if member.bot:
try:
new_bot_role_name = discord.utils.get(member.guild.roles, name = self.new_bot_role_name)
if new_bot_role_name:
channel = member.guild.get_channel(self.channel_id)
await member.add_roles(new_bot_role_name)
avatar_url = member.avatar_url
name = member.name
embed = discord.Embed(
colour = discord.Color.blue(),
title = 'A new bot has arrived',
description = f'Welcome to the army {name}')
embed.set_footer(text= f"{self.bot.user} — System")
embed.set_thumbnail(url= avatar_url)
#embed.set_image(url="")
channel.send(embed = embed)
except Exception as e:
print(f"Missing Permissions: {e}")
else:
new_member_role = discord.utils.get(member.guild.roles, name=self.new_member_role_name)
if new_member_role:
await member.add_roles(new_member_role)
print(f"Se unió un usuario: {member.name}")
the output: Missing Permissions: 403 Forbidden (error code: 50013): Missing Permissions
did you do this ?
bot = commands.Bot(command_prefix='!' , intents= discord.Intents.all())
in the main.py, yes :b
hmm
i thought it was the bot, so I created another one, and got the same error
this is over my head xd
xd, thx by the way
It was a typo :D
it happend to everyone hahaha
What's the full traceback
It was a typo, I fixed it :D
How can I run two bots at once? Like, I can't make two bots in the same file, then do clientA.run(tokenA) and clientB.run(tokenB) at the same time. What else can I do?
it's usually better to run both bots in separate scripts so they can't interfere with each other (like when you want to shut down one bot to update it), but if you really want to run them in one file, you can start them in separate asyncio tasks so both bots share the same event loop with each other, for example: ```py
async def main():
async with asyncio.TaskGroup() as tg: # Python 3.11+
foobot_task = tg.create_task(foobot.start(SOME_TOKEN))
barbot_task = tg.create_task(barbot.start(SOME_OTHER_TOKEN))
# Runs until both bots close themselves, or one bot raises an error,
# or the main program receives KeyboardInterrupt
asyncio.run(main())```
Threading is a solution, but that has it's whole host of other issues
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
Looking for good telegram python devs please dm me
!rule ads
Where can I post this?
Nowhere, this Discord doesn't allow hiring.
Anyone know why whenever I do this, it just stops working when it gets to user.roles? It doesnt give any errors, nothing. Just stops everything except the program. New role will never print
user = guild.get_member(userId) #This works perfectly fine, and gets the user
for i in user.roles:
print("New role")
print(i.id)
I have even tried this, and it still doesnt work. Test 1 and 2 both will print but not 3
print("Test1")
user = guild.get_member(userId)
print("Test2")
user.edit(roles=[]) #Just stops here
print("Test3")
edit is a coro, and naming your object user is misleading as discord.User and discord.Member are very different
So what should I do to fix it?
Await it
Alr, one sec
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
This function is a coroutine.
Note that simply calling a coroutine will not schedule it to be executed:
Should I try the first method again? That I said above?
How is this relevant
It is in this case
my point exactly.
get_... methods return None if the item isn't found in the bots cache
You'll need to use fetch_member
Can you elaborate?
i was just stating that Coroutines don't run on their own just by calling them , they have to be schedule on the event loop to be executed.
After I await fetch_member and await user.roles, it works! Thank you very much
But now I get an issue on this:
I tried doing the await thing but it has the exact same issue, just stopping and not continuing. The data[item][userId]['Prefix'] is what I want, its just not changing it or continuing
user is from a guild.fetch_member()
Any solutions?
Changing user to a guild.get_member() doesn't work since edit isnt a member of get_member.
Is there an error?
Nope, just stops like the problem from earlier
Oh shoot, I didn't mean to say that. There is no error, it just stops
Sorry about that lol
Why do you have to log out and log back in
Typical day after update rollout
Hello, when i try to do "pip install discord", i get that error while i did downoald Microsoft C++ Builds Tools
Nvm, i fixed it
Which type of OS should I use for my Python discord bot
I guess alpine linux if available
How do I connect this to VSC
Alpine isnt available
debian if you're used to Ubuntu
or rocky if you're used to Fedora
i would go with debian but thats just cause i always just debian
Just pick ubuntu
Cause I have a dockerization guide https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
u wrote that?
Yeah
Hello! I have a button that always gives the "interaction failed" message within discord even though everything happens as it should. I read online, that the button needs a response even if it is just empty but all the other buttons in my code work just fine without it.
real
Is anyone aware of a bot that I can use to generate Discord conversations? Possibly one where I could enter their ID and it will simply generate the conversation using their Username + Profile Image. So I can configure the conversation before and then generate the same conversation each time?
skill issue 😈
Snipy you haven't even completed your issue 🥱
Bro that's some wild personal data collection 💀
Haha it's not for malicious intent I just wondered if it was possible
Well yeah just like creating a conversation to be screenshotted
So basically for example like the conversation we are having now, I want to be able to regenerate it but replace your username and avatar with something else
I think there might be libraries that can render discord messages, but in case there are no you can build your custom renderer with pillow
Is there any tutorials or possibly existing software I can use because I have next to 0 coding knowledge
Not that I know of and tbh you picked a very complicated topic for a beginner
I did find an opensource on github which is pretty simillar to what I'm trying to achieve but like everything ever from github it doesn't run properly
Could you link me that project
Sure
@slate swan no dms
can I send links here?
🤡 A Discord.py Cog that provides fake screenshots of discord messages - GitHub - yokharian/ImageDis: 🤡 A Discord.py Cog that provides fake screenshots of discord messages
oh yes I can
The reason you can't run the code is it's not meant to be ran directly
It's a cog that can be loaded into main bot
Holy shit I'm dumb lol do I need to go to developer portal and do all that
Not even that
You don't have the main script
I can help you with tweaking that thing so it works but not rn
That's fine I dont expect you to but that would be great if you could whenever you have the time
https://github.com/Limesssss/FakeDmGenerator this one i think is a finished tool if im not mistaken
calculus hittin'
Is there a way to track how many times a command is run?
Add 1 to an integer in its callback
Dang yall shouldn't help with this problem, these stuffs are mostly for scam ^^
Like fake vouches and stuff
That is not my intent for this software
I don't see any use of it. At least not legitimately
Content creation, being able to generate the conversations rather than typing it all out myself will be much easier
As in, does this functionality already exist in discord.py, or are you asking how to implement it yourself?
hi im not sure if i use this or the help thread but im having trouble with this code
for user_id in users:
member = interaction.guild.get_member(user_id)
if role1 in member.roles:
for _ in range(int(r1_entries)):
users.append(_)
winner = await client.fetch_user(random.choice(users))
await msg.reply(f"Congratulations {winner.mention}! You won the giveaway! :tada:")
users.clear()
there is a list with user ids it fetchs the user but i cant find a way to check the users roles member.has_roles() and member.roles has no attribute to it the role is defined in the async def as role1: discord.Role=None
You’ll need to specify what you need help with
finding a method to get to check the users roles
discord.Member.roles returns the users roles in a list
Hello, I'm still at the beginning of coding and i need some help. The bot wont respond to my "hello" command. Any ideas why? (you can js dm me i guess)
||import discord
from discord.ext import commands
TOKEN = ''
intents = discord.Intents.default()
intents.all()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
print("-----------------------------------")
@client.command()
async def hello(ctx):
await ctx.send(f'Hello {ctx.author.name}!')
client.run(TOKEN)||
it was a stup1d warning i fixed it 👍
Can I limit SlashCommands usage to a certain channel? I mean, the commands will only be visible if you're in that channel. Is that possible?
Only through the discord integrations ui
You cannot change the visibility with your bot
but can I check if the person that will use it is part of a ID's list for example, if not, then send an error message?
yes
Yeah sure
how xd?
i would suggest putting a role or perm check
slahscommand*
is it in the docs?
yeah they have decorators for it
A hands-on guide to Discord.py
got a few examples here
yei!
thanks!
I have a main file called bot.py that inits the pool connection to my database. How should I go about having a connection to the db in cogs?
async def setup_hook(self):
self.pool = await asyncpg.create_pool(user='postgres', password='root', database='bipolar', host='localhost')
self.db = self.pool```
Code in `setup_hook` ^
Probably just access your bot object through ctx.bot/interaction.client inside command callbacks
Or pass your bot object in as self.bot when instantiating cogs
example?
ctx.bot.db works
Question: how do you know when to make a Help topic vs coming here to post?
If it's a simple question you come here. if it would require a lot of attention make a post
👍
hey guyss, can someone please tell me why this isnt working?
It helps if you explain what the issue is vs what you expect
ok so, I'm making a bot, using cogs, but I wanna make it load all cogs in a folder [cogs], but I'm not sure how To make it do that
Here's what I have so far:
import discord
from discord.ext import commands
import os
TOKEN = "********"
class Nxghtmare(commands.Bot):
def __init__(self):
super().__init__(
command_prefix="!",
intents=discord.Intents.all()
)
Nxghtmare().run(TOKEN)```
does anyone know how i can make a bot with slash commands? i have this code from the docs but it doesnt work
import discord
from dotenv import main
main.load_dotenv()
TOKEN = os.getenv('BOT_TOKEN')
bot = discord.Bot()
@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
bot.run(TOKEN)
print('logged into discord bot')
```the error i get says
bot = discord.Bot()
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
I'm struggling to figure out how to use Groups within Cogs, I keep getting TypeError: Command signature requires at least 1 parameter(s)
@commands.group(name='list')
async def list_group():
pass
@list_group.command(name='duplicates')
async def _list_duplicates(self, ctx: commands.Context) -> None:
...
- You need to register slash commands
- The
bot = discord.Bot()
Needs to be replaced with
bot = commands.Bot(command_prefix="!", intents=intents)```
And once it's replaced, make sure to pass your intents through too.
I wrote a basic framework that I build my bots around, it has branches for hybrid and slash command based bots and contains a few utilities
https://github.com/Sm1mg/discord.py-bot-core
@ornate linden can you help with this?
sure yeah
do you want to make it automatically load every cog in the folder or can you enumerate it in the main file?
also, use a .env to store your token instead of being in the file
automatically load all .py files in the cogs folder
you can have os list all of the files in the directory and run self.load_extension("cogfoldername.cogname") from inside your commands.Bot subclass on each of them
afaik there's no way to do it that's more automated than that
I managed to do it like that last time, I just lost my files, it would load all the cogs inside the folder
i got the bot to log in, but how do i make it use slash commands?
I'll write a script that does it that you can drop into your subclass
I'm not sure with slash commands.
use disnake and you can .load_extensions lol
dpy is so behind in terms of stuff like this
@desert kiln ```py
async def setup_hook(self):
this won't play nice if you have subdirectories
cogs = os.listdir("cogfolderpath")
for cog in cogs:
self.load_extension(f"cogfolderpath.{cog}")
especially if you are just starting i would highly suggest using something other than dpy
pretty sure every lib other than dpy has .load_extensions
so you can load a folder of cogs
Cog didn't load
is it an fstring?
try moving it into the __init__ instead of having it inside setup_hook
it was my method signature, i needed to include self and ctx
tried it, it didn't work
ah i know what's wrong
my bad, the fileextension shouldn't be there
change it to {cog[:-3]} and it should work
where do I replace that
async def setup_hook(self):
# this won't play nice if you have subdirectories
cogs = os.listdir("cogs")
for cog in cogs:
if cog == "__pycache__":
continue
await self.load_extension(f"cogs.{cog[:-3]}")
found another problem with the pycache
should be good now
ok I ran it, but no "cogs loaded" message appeared when I ran it
that doesn't happen automatically, you could put a print statement in the __init__ of the cog
or add ```py
...
continue
await self.load_extension(f"cogs.{cog[:-3]}")
print(f"Cog {cog[:-3]} loaded!")
hm
i don't know, but what I wrote is effectively the same as load_extension(cog1) load_extension(cog2) etc
I hate to say it, but it works for me..
so, i am trying to make this function where with a slash command, it locks the channel at the given lock time and unlocks the channel at the given unlock time.
i created the function and i even add it to the mongodb and it works fine, no error in the database part so it stores the date, but it doesn't lock the channel when lock time has been reached.
it sends a message saying "locking channel in in an minute and then it doesn't lock once the timer is finished. can you help me?
and also, i keep getting this error when i run the command.
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000001F2AB202470>:
Traceback (most recent call last):
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 895, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Kaushik\Documents\Programming\r-IGCSE-Beta\lockdown.py", line 166, in Channellockcommand
await interaction.response.send_message(f"<#{channelinput.id}> is scheduled to lock on {unixlocktime} and unlock on {unixunlocktime}", ephemeral=True)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 896, in send_message
await adapter.create_interaction_response(
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 195, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interactio
code is in #1186487018121871361
Do I need C++ to do
pip install discord
im getting the same errors right now too
seems to be sporadic but primarily non-functional. sometimes it will work and sometimes it won't and i don't know why. functions that have always worked are now doing it to me too
https://downdetector.com/status/discord/ looks like its a server outage maybe
You have to respond to the interaction within 3 seconds
You cannot respond twice
place await interaction.response.defer() right after async def..
it just started working again randomly for me. no issues now. didnt change anything
can you help me with the lock part?
Don't ask to ask please
If you have a question, send it and somebody will help if they want to
Many other people can help you as well
i alr sent it
so, i am trying to make this function where with a slash command, it locks the channel at the given lock time and unlocks the channel at the given unlock time.
i created the function and i even add it to the mongodb and it works fine, no error in the database part so it stores the date, but it doesn't lock the channel when lock time has been reached.
it sends a message saying "locking channel in in an minute and then it doesn't lock once the timer is finished. can you help me?
@client.event #for ads cards:-
async def on_reaction_add(reaction, user):
message = reaction.message
if await toolfn.check_if_kco(reaction, user, client, message):
embed =toolfn.collection_cards(message, reaction)
channel = reaction.message.channel
await channel.send(embed=embed)
asyncio.sleep(5)
else:
print("error")```
Hi, this is my half code of what I'm actually trying to build.
So, when a user reacts on a specific message with specific emoji, this will trigger, and it'll copy the message and send it in the channel as an embed but this is just half of what I tried to build.
Actually, I want the bot to hold for some time and wait for the user to edit their messages ( like for 5 seconds) and when the user edit their same message which was sent in the first place, then the bot will also save that new message content as new variable, and then the bot will send the new message which will contain both messages ( first sent by the user + 2nd after the message is edited)
And I am just trying to get mine to respond in my server chat...
@final iron ?
message.content isnt working for some reason, anyone know why?
^ tryna create where i can monitor people message
Do you have message content intents enabled?
How do you enable message content intents? Are they the same as just the normal intents or are you talking about something different?
if I use py async for msg in channel.history(limit=None, oldest_first=True):
and a message is sent in that channel while the loop is running, will it be ignored or entered into the loop?
how to make the bot fetch the message id right after it sends a message?
message = await ctx.send(...)
message.id
or alternatively await ctx.send(...).id
from some very rough testing, I think that it doesn't
@blacklist.error
async def blacklist_error(self, error, ctx):
if isinstance(error, commands.errors.MissingRequiredArgument):
await ctx.send(embed=discord.Embed(description=f"> you can't blacklist nothing silly :3"))
elif isinstance(error, commands.MissingPermissions):
await ctx.send(embed=discord.Embed(description=f"> you don't have the required permission to do this! >:3"))```
@commands.command()
@commands.has_permissions(administrator=True)
async def blacklist(self, ctx, word):
async with self.db.acquire() as c:
a = await c.fetch("SELECT blacklisted FROM servers WHERE sid = $1", str(ctx.guild.id))
if word in list(a[0]['blacklisted']):
await ctx.send(embed=discord.Embed(description=f"> {ctx.author.mention}: {word} is already blacklisted :3", color=self.pink))
else:
a = list(a[0]['blacklisted'])
a.append(word)
await c.fetchrow("UPDATE servers SET blacklisted = $1 WHERE sid = $2", a, str(ctx.guild.id))
await ctx.send(embed=discord.Embed(description=f"> {ctx.author.mention}: {word} has been blacklisted :3", color=self.pink))```
No error gets printed, it goes into the blacklist error command (I checked with else statmeent). It just doesn't go to missing perms or missing arguments one even though both errors I've gotten are those.
Ping me if u know how to fix it :3
Hi Guys
How should I change the code to
The user who sent the message gets the role, not the user who added the reaction.
@bot.event
async def on_raw_reaction_add(payload):
channel_id = 1186540419354468353
if payload.channel_id != channel_id:
return
emoji = '👍'
if payload.emoji.name != emoji:
return
channel = bot.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
user = await bot.fetch_user(payload.user_id)
role_id = 1091865008268386314
guild = bot.get_guild(payload.guild_id)
member = guild.get_member(payload.user_id)
if role_id not in [role.id for role in member.roles]:
return
role = guild.get_role(1091865047682261013)
await member.add_roles(role)
await channel.send(f'{user.mention}, You have been added to the identity group {role.name}!')```
Ugh
get msg author
!d discord.Message.author
Hey Can Anyone help me with my discord bot i am getting so many errors
A hands-on guide to Discord.py
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000001D4AC417460>:
Traceback (most recent call last):
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 895, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Users\Kaushik\Documents\Programming\r-IGCSE-Beta\F-lock.py", line 135, in Forumlockcommand
await interaction.response.defer(ephemeral=True)
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 679, in defer
await adapter.create_interaction_response(
File "C:\Users\Kaushik\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 195, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
this is the new error
how to solve it?
how do I get the id of a user who is mentioned in a message, regardingless if its an @ mention or the ID or their name. For example someone types "@karmic shore" or "1017915595083231283" or "heromaex"
the text that Im getting is ONLY that so no need to search for it
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
You'd have to somehow search for the last 2 yourself
IDs you can use a regex and then match the user
Name however, you'd have to look at every single word in the message and check if a user has this as username in the guild/all guilds - which is definitely not recommended
Also note that names can be duplicated
Nicknames, at least
I see yea
@bot.event
async def on_message(message):
channel_id = 1186540419354468353
if message.channel.id != channel_id:
return
guild = message.guild
member = message.author
role_id = 1091865008268386314
role = guild.get_role(role_id)
if role not in member.roles:
return
await member.add_roles(1091865047682261013)
channel = guild.get_channel(channel_id)
await channel.send(f'{user.mention}, You have been added to the identity group {role.name}!')```
hey guyss, can someone tell me whats wrong with this?
await ping.delete() u missed the ()
OHH, RIGHTT
i forgot that ()
thank you so much
np
Anyone know if there's a way to see if a DM you send is getting caught in someone's "Message Request" pile?
For context, the "you've never joined voice before" notification we have for the bot will attempt to send a message to someone's DMs and if that fails, pings them in the #voice-verification channel. Needing to see if we can re-route to the channel if we're getting thrown into the Message Request pile as well
hmm never thought about this before iirc message request happens when discord flags a dm as spam iirc
I don't believe so, no
also if this is for the button thing the feedback message should probably be ephemeral and leave DMs out altogether
IIRC that's kind of the intention if ephemeral messages
I agree. Ephemeral messages would be a good alternative. Discord doesn’t return the information when your message is hidden in the message requests section
Might depend on user settings. For me, every DM sent to me from somebody i don’t have an active DM channel with or have friended gets put into the message requests
This isn't for the feedback message. The thing I'm mentioning there is purely when they join VC for the first time
I do only use ephemerals when they hit the buttom
And I wouldn't be able to use an ephemeral message on this since it's not being triggered from an interaction, unlike the button
i have a problem i can't import discord in visual code studio how can i fix that?
pip install discord
hey guyss, can someone tell me whats wrong please, its giving me this error and i dunno what am i doing wrong
can you show us how you're starting your bot
In a DM with a user, the Bot says "Hi, press the button" and there's going to be a button, but when the user press the button I want that original message to be edited to something else, and so on. Or delete the message and send another one, to keep it clean. How can I archive that?
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None, suppress_embeds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
Oh, fantastic, thanks!
How do I set up a Group in a Cog using slash commands?
I found GroupCog in the documentation but there's just a few commands I would like to be in a subcommand
I just found AppCommandGroup, is that what i'm looking for?
@ornate linden
huzzah, StackOverflow saves me again https://stackoverflow.com/questions/76531100/how-to-code-sub-commands-for-discord-py-but-they-are-slash-commands-and-in-a-cog
pulled straight from umbras gist 😭
are nsfw discord bots against tos and if so are they allowed if commands may only be executed in nsfw channels? (asking for @vapid parcel cause he's lazy!!)
Nah bro pinged me 
yep
More like i just didnt wanna ask 😭
mainly cause I wanna sleep

If anyone's up for it, I need a rubber duck.
I've learned how to do buttons, and I've gotten them to output values in their own function. I want that value to be accessible to the function that's calling it. The guides I'm seeing put the buttons in a class. Somehow, the class thing is not working with my brain bc I'm unsure how to get it to return a value from that class one the user has hit the button.
Is it as simple as return ClassName == "cats"?

It could also be that I'm still having a hard time with the class object
that would return a boolean. perhaps you just wanted return "cats"?
Would that make the result of the class equal cats?
I suppoer Im having a little trouble with the idea of getting buttons to do more complicated operations
the result of whatever function it's in
if you want to show us your code that'd be helpful
It is a complete mess atm since i've gone in a few directions to try and get what I want
I'll give a breakdown of what I want to do:
This is for adding to a database. Users start the bot and press one of a few options [Create, Delete, Modify]. For create, they can then type in the name of a user on the server and a character they're playing to add them to the sqlite3 database. For modify and delete, they'd be able to sleect from existing player/character combos and do stuff to them
I've gotta do that sleep thing, so please ping me with any replies after this point
Yeah nsfw commands should be in nsfw channels. Idk if it’s like official but every bot list website has it in their rules so probably yeah
Also if ur under 18 there’s also stuff for making nsfw bots
It's very self-explanatory
that sounds reasonable enough. if you provide us with your code we can give you more concrete help
I need help, I've done with before, but I lost files for it, I need help with the cogs loader, I don't mind specifying the cogs .py files, as I wanna do it like that anyways
Nevermind, I've managed to figure it out, but I do need help with command for reloading the cogs
what is the API endpoint to create a channel?
/guilds/{guild}/channels
https://discord.com/developers/docs/resources/guild#create-guild-channel
hey guyss, can someone tell me whats wrong please, its giving me this error and i dunno what am i doing wrong
text is better then a screen shot.
!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.
Which do you guys recommend:
Discord.py, py-cord or disnake?
Used discord.py in the past, but a while ago. Didn't really like how they were implementing slash commands...
