#discord-bots
1 messages · Page 293 of 1
whats the best way to edit an embed message sent by the bot?
im currently doing await interaction.response.edit_message(view=self)
but when the message gets edited, it disappears from a while from discord, just a bit, few miliseconds
but ive seen other bots without this small delay
send code here
both or one in particular?
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.
Hello my bot no longer responds to my command I don't know why 0 error message
import discord
from discord import app_commands
import asyncio
import random
import discord.member
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix="+", intents=intents)
client.remove_command('help')
@client.event
async def on_ready():
print('Bot ready')
@client.command()
async def owner(ctx):
print("owner")
await ctx.send("Halycon !")
client.run("token")
maybe ur token expired? idk if that can happen, but try getting a new token
No
does the "bot ready" get printed?
@slate swan
Why remove !help?
You could have used it to see if your Owner command was working
Callbacks from buttons have the signature of (self, interaction). It's better to subclass and create your views the OOP way to prevent these sorts of issues, rather than what you're currently doing with the assignments.
from discord.ext import commands
from discord.ui.button import Button
from discord.ui.view import View
class ButtonView(View):
def __init__(self, ctx):
super().__init__()
self.ctx = ctx
self.add_item(Button(style="primary", label="Haz clic aquí"))
async def interaction_check(self, interaction):
return interaction.user.id == self.ctx.author.id
async def on_timeout(self):
pass
async def on_button_click(self, interaction, button):
await interaction.response.send_message("¡Has hecho clic en el botón!")
class BotonCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def boton(self, ctx):
view = ButtonView(ctx)
await ctx.send("Presiona el botón:", view=view)
async def setup(bot):
await bot.add_cog(BotonCog(bot))```

example how to add buttons to view
Bro didn't use decorator
what did you try??
The example you sent me from git
^
import discord
from discord.ext import commands
class ButtonCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def boton(self, ctx):
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
view = Confirm()
await ctx.send('Do you want to continue?', view=view)
await view.wait()
if view.value is None:
await ctx.send('Timed out...')
elif view.value:
await ctx.send('Confirmed...')
else:
await ctx.send('Cancelled...')
def setup(bot):
bot.add_cog(ButtonCog(bot))
first of all never nest a class inside other class
Oh he actually nested a class inside a function, i didn't notice at first
Worse practice
Can someone help me make a timeout command?
what you have so far?
nothing 
can you help? @slate swan 
A hands-on guide to Discord.py
let me know if you understand everything in here
I don't know much about python sorry
I will try what you said 
not tryna be rude but discord bot isnt a good project to start python journey
it requires many advanced topics like OOP, decorators, async/await syntax
with app_commands.choices, does the value need to be a number?
true_false = [
app_commands.Choice(name=True, value=1),
app_commands.Choice(name=False, value=2)]
or can I put whatever?
like say I want the value for True to be "Happy Days" instead of 1, can I?
it supports int, str, float
neat
the discord api supports the boolean type too, dont think you need to use choices
Wot.
So I can do: async def usersettings(self, interaction: discord.Interaction, setting: app_commands.Choice[int], option:bool):?
discord/app_commands/transformers.py line 713
bool: IdentityTransformer(AppCommandOptionType.boolean),```
true and false
thats what shows up
neat
yo guys, im pretty much at 0 when it comes to dsicord bot dev, i've done py for a few years now (althoug have baerely coded in a few months ive basically forgotten everything)
what resources do yall recommend me to start with? ty
If you need a refresher on python, I would suggest taking a small course like py4e or going through a book like Automate the Boring Stuff (!resources)
Once you're comfortable with basic python and OOP you will be able to navigate documentation on your own, which is important
thank you 🙏
Aside from that you can check out https://fallendeity.github.io/discord.py-masterclass and https://pythondiscord.com/pages/resources/guides/discordpy/
Those are tailored to discord.py specifically
Show output of
import discord
print(discord.__version__)
wut
What version of discord are you using?
import discord
from discord.ext import commands
discord.py-1.7.3
Update it to latest
nah then
Intents came in discord.py 2.0
will "from discord_slash import SlashCommand" not work
Yeah it won't work it's an old lib
yea thast why i need to use old lib
Instead u should dpy in built module
on wich lib work "from discord_slash import SlashCommand"
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Delete it it's redundant
You can check how to create slash commands in dpy in above gist
wich is better
discord-py-interactions
or
discord_slash
" for slash cmds "
why do you want to use a third party library?
what should i use ?
bc i want to make slash cmds
You was answered like ten times that slash commands are already built into discord.py
Also you can try disnake or pycord if you don't like discord.py so much
just use discord.py?
bro i told 10 times, its for me harder if i try to make slash cmds with discord.py
and idk wich version
Then use what you like. But we can't really help with it
wich py version should i use for slash cmds with discord.py
doing pip install discord.py -U should upgrade it to the latest version (which has slash commands)
3.8 or above
3.8 ??????
Python 3.8, yes
💀
I mean, you asked the question 
`import discord
class DMBot(discord.Client):
def init(self, token):
super().init()
self.token = token
async def on_ready(self):
print("Bot ist bereit!")
async def on_message(self, message):
if message.author == self.user:
return
if message.content.startswith("!dm"):
recipient = message.mentions[0]
message_content = message.content[4:]
await recipient.send(message_content)
print(f"Nachricht an {recipient.name} gesendet: {message_content}")
def main():
token = YOUR_TOKEN_HERE
dm_bot = DMBot(token)
dm_bot.run()
if name == "main":
main()`
like its not work
if i try to open it, its autoclose with out a error
ps : i am new in developing bots
oufff
guys help me out i am stuck
If it's discord.py then it's surely invalid
Bot doesn't take token, but run does
intents are required argument for bot
And you will get an error by running this. It can't just autoclose
If it autocloses, it seems you are trying to open it with just a double click
Guys, is there any way that whenever someone sends an email I would setup somehow an integration and it would send me a message on discord as well? Ik it is kinda a stupid question 😄
Yes
and how? 🙂
By using Google on how to interact and use SMTP servers
sws = clean_message2.replace(" ", "")
allowed_words = set(['**1**'])
banned_words = "|".join(map(re.escape, profanity.CENSOR_WORDSET - allowed_words))
# Find if any banned words are in the message
if re.search(banned_words, replacespaces(replacespecialcharacters(replaceDoubleCharacters(sws))), re.IGNORECASE):
key = f'antibadwords:{message.guild.id}'
if r.exists(key):
await message.delete()
embed = discord.Embed(title="No bad words allowed", description="Please refrain from using inappropriate language.")
embed.set_footer(text="Censored by better-profanity")
log = r.get(f"logs:{str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author.mention}'s message was deleted.")
embed.add_field(name="Reason", value="Contained bad words.")
embed.set_footer(text="Censored by better-profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"Bad word detected. Logs: {message.guild.id}")
```this code is deleting strings with bad words with no spaces for example its deleting "f***hi" i dont want it to to delete that
i would want it to delete f** hi
not f***hi
just dont replace the space with empty string then at the top?
can i have a tasks.loop within a button class?
And what you want to achieve with that?
when a button is clicked starts the loop and checks for some confirmations or something
why does it has to be done in a loop
i cant think of another way to do it
well you can do mytask.start() on button click
and then .cancel() or .stop() or other action
but within that loop im gonna be needing some stuff from my database. and i am going to need to use WHERE ... so that the info i get from the databse corresponds to the right users. i dont kniw how i'd do this
start(*args, **kwargs)```
Starts the internal task in the event loop.
Nope
@slate swan
However, there are lots of websites, especially the documentation, which teach you the basics and can help you find the things you need
yes.
It takes no argument
.
ok great
Unless you're actually using them
if i do interaction.channel.id there, would i have to do this here?
@tasks.loop(seconds=60)
async def my_loop(interaction.channel.id):```
No
i can just do my_loop()?
uh
First thing you learn about functions, their parameters
Is there a guide on making a discord bot in python??
i just wanna know about loops atm
def blah(myAwesomeParameterWithoutDotsOrTryingToGetAnAttribute):
print(myAwesomeParameterWithoutDotsOrTryingToGetAnAttribute.nowICanGetItsAttributes)
Is there a guide on making a discord bot in python???????????
Would you mind stop spamming your question that you can search on Google yourself??????????????????????????????????????????????????
i cant find anything and sorry for spamming
lmfao that's straight up a lie
so once ive got my_loop.start(interaction.channel.id)
what do i pass in the def my_loop():?
it just tells me how to turn on a bot
✨ a parameter ✨
yes, but how would i be able to get my interaction.channel.id in the loop
✨ By using that parameter ✨
so channe1_id?
!e ```py
def my_func(x):
print("yay, i got x:", x, "!!!")
my_func(123)
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
yay, i got x: 123 !!!
you can name it anything you want

and it will give my my interaction.channel.id?
if you will pass it to the start
Absolutely, and once you got that use the documentation to find what you need. Note that the library is made for people with advanced knowledge in Python
Try it and see moment
ok
so ur telling me not to make it
yes, ive done my_loop.start(interaction.channel.id)
If you don't have an advanced knowledge of Python, correct
A hands-on guide to Discord.py
The name 
can i use .stop within the tasks.loop?
Read first page and
The default intents contain all intents except for the
discord.Intents.members,discord.Intents.messagesanddiscord.Intents.presencesintents.

i know i already told it to the person who made it

but i guess they too busy to correct it
a month ago 
🧐
There, maybe a click is faster 

i just told them there is a bug and forgot they forgot 
Probably want to squash and merge PRs so that you don't always have 2 commits filling up for nothing


A hands-on guide to Discord.py
there you go

ty ty

how do i give my bot a prefix
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
it's required tho
you couldn't skip it
idk lmao i did what that website told me to
this one
It's giving the prefix there
?
whats ctx
Context instance
it's always given to the prefix commands by discord.py library
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
ohh alr and ty for the prefix works
how do i make a bot message someone e.g !owner [message] then i want it to msg me
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.User.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**.
whats that
can you help me
After that you use the send method on it to send a message
They're helping
I already helped you, those are the two functions you need

which one do i type in first
Remember that though
oki
As I said, you first get a user object and then use send on it
Depends
Use Cogs
If you have one command, not really necessary
Hi
how do i link one file to another so i can do it in multiple
If you want to make the average moderation/multipurpose bot that exists already in 48292728 copies with all the same pointless commands, then you likely want to use cogs as mentioned above
im making custom tryna learn
Use cogs if you feel it's necessary
Do you have a good tutorial for it?
By using Google to find a documentation around it
not yet 
uh ok
FallenDeity/discord.py-masterclass#21
its on the way
Ohh
this is so hard bruh
It's called OOP and is something you must know, so if you don't know it - you're looking at the wrong project to work on
As mentioned before multiple times, it's a library for advanced developers
Hay guys 🙏
Yes
yeah
you do that like for a normal channel
A forum thread is a normal channel
!d discord.Thread.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**.
So you can send like you'd do in any other channel
I am a bignner in python3
i am advinced
That's cool 😎
@formal basin so, you want a cooldown on the message filtering? what would that entail?
would only every couple messages get filtered?
is there another way to stop flagging too many times at once?
because many messages are being sent so the bot has too read those messages and check for bad words
at once
what do you want it to do instead though? if you don't want it to be filtering every message, then which messages do you want to be filtered?
So you want to prevent users from sending messages too quickly?
Hay I am a. Bignner in python3
hmm
👋 any question you wanna ask?
what would you recommend?
Yes , how many months of experience you have about python programming
i'm not sure, a bot which only filters certain messages doesn't sound like the most effective filter :P
1,5-2 years
why is the bot dealing with "too many messages at once" a bad thing?
@slate swan Wow 😲😳
idk the heartbeat gets blocked
i dont make the rules
You also have knowledge about Ai
Me when synchronous code in asynchronous environment:
Limit of what?
hrmm, that sounds like the regex check is taking too long, and so blocks for longer than it should - so then when discord tries to contact the bot to see if its still running (the "heartbeat"), it gets a super late response
nope but if you wanna ask a question about ai check out #data-science-and-ml channel
that exactly whats happening
But i have some experience about Ai
how many requests are allowed at certain time
thats great 👍
how big is this list of banned words, can i ask?
let me check
What is your intrest in python . Game developer? Data analytics, GUI development? Or something else
over 900
maybe 912 or 907
somwhere there
generally discord bots if that can even be an intrest

Ook
Do you have any public? 
Not for testing something
public one on the way
https://github.com/Skurczybyki/bot
making it with one friend
To be honest, I've mostly made bots to visualise something I made 🐈
You know about Chat GPT 😃❓😂
maybe I should check without regex then if its true then check with regex?
hrmm okay
well, obviously since its taking too long to run the check, the first thing i'd do is see if there are any ways to speed this function up
could you paste the whole on_message listener?
how could i do that?
!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.
ok
you can just do f":regional_indicator_{letter}"
what would letter be =?
👍
i guess a letter right?
@slate swan with the masterclass why is tested on python 3.9 and saying on the site it's 3.8+?
The .replace calls might be taking some time there
that emoji-cleaning code looks a little more complex than it needs to be - you're running emoji.emojize, just to then convert those emojis back to their words, and then to further convert the words back into just letters
what do you think it means
i feel like i saw that already can you show me though
because you have the message¿
.github/workflows/format-and-lint.yml line 21
python-version: '3.9'```
what can i do to make it faster?
im confused
but how will it get the letter from the message?\
did you wrote that code?
half me and half ai
@shrewd apex blame on you
write it by yourself and then ask for help :p
Me when re.sub 😔
IIRC, the message content just already contains emojis in their emoji form, rather than the :emoji: form, so that emoji.emojize step isn't doing much
then on top of that, your chain of .replaces could be replaced with a .translate, to map all those regional indicator emojis straight to the letters they represent
mkdocs.yml line 57
- https://docs.python.org/3.9/objects.inv```
whats that
we can change it in the config file
No clue but it's 3.9
it lints and formats for version 3.9
tbh thats the oldest version of python i have used so far 😅 i did use 3.6 with some ubuntu default installs but that hardly counts
most of my projects range from 3.9 - 3.11
3.12 💪
Why is the masterclass even suggesting at least 3.8+ 😢
were there any huge changes from .8 -> .9 ?
Just force them to use 3.11
discord.py is 3.8+
iirc discord.py
egjactly
sub interpreters look fun
The version number is the biggest noticeable change.
tru
for their own good
lmao

hm ok
feel free to make edits on second note tho
The thing that is bothering me the most is the way the Python installation is explained. Just use Brew, apt-get (curl) and Chocolatey. @slate swan
feel free to open a PR 😄
i think instead of all that, you could do something like this: ```py
a dictionary which maps the regional indicator emoji codepoints to their regular character codepoints
the numbers sorta look magic, but they work - you can poke around and figure how how this works by looking at what the result of chr(0x1f1e6) and chr(0x41) is
emojis_translation_table = {e: c for e, c in zip(range(0x1f1e6, 0x1f1ff), range(0x41, 0x5a))}
@client.listen()
async def on_message(message):
sws = message.translate(emojis_translation_table)
I- most likely will..
but where would it get the emojis from?
!e print({e: c for e, c in zip(range(0x1f1e6, 0x1f1ff), range(0x41, 0x5a))})
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
{127462: 65, 127463: 66, 127464: 67, 127465: 68, 127466: 69, 127467: 70, 127468: 71, 127469: 72, 127470: 73, 127471: 74, 127472: 75, 127473: 76, 127474: 77, 127475: 78, 127476: 79, 127477: 80, 127478: 81, 127479: 82, 127480: 83, 127481: 84, 127482: 85, 127483: 86, 127484: 87, 127485: 88, 127486: 89}
That's an interesting way to uhh write numbers.
what kind of permission am i missing?
ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Documents\GitHub\RP-Utilitites-Beta\cogs\ActionCog.py", line 42, in on_message
webhooks = await message.channel.webhooks()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\channel.py", line 564, in webhooks
data = await self._state.http.channel_webhooks(self.id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Whatever you're trying to do at line 42 in the file ActionCog.py
!d discord.TextChannel.webhooks
await webhooks()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets the list of webhooks from this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
well i dont have a mac so feel free to edit that part ;-;
i never knew range could take hex values 😳
They're just numbers in the end 
true
You can use them as a replacement to numbers anywhere
even could use octal system if you wish
yeah just didnt know u could pass them to range like that
ig any base should be possible right?
ok done now checking
yes its all an int
mhm
@shrewd apex Any way to run the site locally? Never worked with mkdocs a lot.
Any recognized base yeah
mkdocs serve
u install dependencies then mkdocs serve
AttributeError: 'Message' object has no attribute 'translate'
or if you use poetry then portry run mkdocs serve
you can do message.content
!d str.translate
str.translate(table)```
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via `__getitem__()`, typically a [mapping](https://docs.python.org/3/glossary.html#term-mapping) or [sequence](https://docs.python.org/3/glossary.html#term-sequence). When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return `None`, to delete the character from the return string; or raise a [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) exception, to map the character to itself.
You can use [`str.maketrans()`](https://docs.python.org/3/library/stdtypes.html#str.maketrans) to create a translation map from character-to-character mappings in different formats.
See also the [`codecs`](https://docs.python.org/3/library/codecs.html#module-codecs) module for a more flexible approach to custom character mappings.
its a string method
🧐
yeah so message.content instead of message
correct
!e print(type(0o456))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<class 'int'>
by recognized u mean ones which have representation like 0b 0o 0x etc?
There was no spoon option

Though to be fair I prefer to use hex when it makes sense, e.g. dealing with memory etc.
never used octal system though
Hi
hex and binary most used
@plain pollen its still heartbeat blocked. But it is a little faster
yeah
Hay bro.
👋
look dealing with messages in on_message is hardly a reason to block heartbeat
Would make sense when dealing with system permissions, other than that it's pretty meh
Can you tell me some thing?
since the gateway client for heartbeat runs in another thread
so you are probably doing some blocking task
dont permissions usually use bitwise flags
well it reads like 20 messages in 1 second
I mean system permissions, like file system permissions
unix file perms
yeah
i see
it needs manage_webhooks
how do i enable it by code?
Anyone tell me the best course to learn python.
thats not an issue it wont block the heartbeat
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
u should check for blocking tasks
Or ask in #python-discussion
either grant it on discord server settings or request it when adding to server
what is an issue that would block heartbeat?
To learn python programming
time.sleep(60)
Yeah, click that blue text
anything that blocks the main thread
blocking code 😵💫
time.sleep?
like pillow tasks, io bound operations
@formal basin check out !blocking command
also this https://discordpy.readthedocs.io/en/latest/faq.html#what-does-blocking-mean
it puts the main event loop / thread to sleep
⚠️ !blocking sends long embed preferably run in #bot-commands
asyncio.sleep is the alternative for async operations
i use that
yeah well look at other parts of your code
i would recommend this https://automatetheboringstuff.com/
on_message and received messages and working with them will not cause heartbeat errors at most ur bot will response to those messages will be a bit delayed
Okay soo maybe i will need to re-invite my bot?```
ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\User\Documents\GitHub\RP-Utilitites-Beta\cogs\ActionCog.py", line 42, in on_message
webhooks = await message.channel.webhooks()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\channel.py", line 564, in webhooks
data = await self._state.http.channel_webhooks(self.id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
well it does not have permissions
Ah yes, let's send a second time the exact same long traceback
@slate swan Let me check it also , thanks
Thanks bro for help 😁
just give it admin
edit the perms from roles
yo this your warning?
Another optimization could be to use a single regex instead of running a separate regex for each word
yep
let me show you the error
!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.
ok
Anyone form India 😁❓
🧐
https://paste.pythondiscord.com/3PIA it clearly says the regex
ot moment
this full traceback?
yes
Btw when setting up the project pyright got an absolute stroke because the command is fully executed in the entry in the commit hook.
masterclass?
Yep entry is used as command entry not as execution lol
weird reges shouldnt block
So for some reason pyright couldn't see all my deps
are you opening files or smn here?
hmm
this is in the pre-commit hook?
.pre-commit-config.yaml line 54
entry: poetry run pyright .```
^
i guess thats it
nope
I changed it to ```yml
- repo: local
hooks:- id: pyright
name: pyright
pass_filenames: false
entry: poetry
command: run pyright .
language: python
stages:- commit
- id: pyright
Then it worked.
entry should be poetry run though
Or poetry shell
poetry run should by default use the poetry env
maybe i might
if u ran poetry shell previously then pyright . alone would suffice
Hence why I was so confused.
It shouldn't be..
do check once
Yoo. I leaned many things about python 😁😁
feel free to open a pr time
tbh i feel like set comparisons would be much faster than regexing every message
bro speed ran didnt u just ask for resources a few moments ago?
Yeah I will open a PR for this with the deps I updated for now.
Yes , i and I read some topics i python3 and learn many bignner level topics 😁
what deps does it need though
well its a set not a file
ic good for you
Hamm
can u show the function that ur using once
Now going to solve some basic problem of python .
atb
for pattern in new_words_list:
if re.search(pattern, sws, re.IGNORECASE) is not None or re.search(pattern, replaceDoubleCharacters(sws), re.IGNORECASE) is not None or re.search(pattern, replacespecialcharacters(sws), re.IGNORECASE) is not None or re.search(pattern, replacespaces(sws), re.IGNORECASE) is not None:```
Any one give any question ❓😁
it checks about 900 words
no can u break this huge if statement into parts to see which part is blocking i think its likely one of those custom functions
go to leetcode or hackerrank and solve some then you will know if you understood topics
ok
I think function is defined by keyword def .
damn op ^^
send me code for one of those functions btw
Nothing I just updated it.
also why is not None for everything with or just use any()
Bro when I learn more about python and got some more experience then I go . Now I got questions from chat GPT 😁
def replaceDoubleCharacters(string):
lastLetter, replacedString = "", ""
for letter in string:
if letter != lastLetter:
replacedString += letter
lastLetter = letter
return replacedString
def replacespaces(s):
s = replaceDoubleCharacters(unidecode(s))
return s
def replacespecialcharacters(s):
special_characters = r"[.\/,'|*=\-_`!<>+$%^?!!1234567890@ ]"
string_without_special_characters = re.sub(special_characters, "", s)
string_without_special_characters= replaceDoubleCharacters(string_without_special_characters) or unidecode(s)
return string_without_special_characters
i never knew this ‼️
No one does 🙀
thank you for sharing this information sir
Why ❓
i sleep when professor sayed "function"
Bro I have just a doubt.
?
About that code .
when i use the one with no functions it gives me this warning
2023-08-27 15:26:04 WARNING discord.gateway Can't keep up, shard ID None websocket is 10.7s behind.
but doesnt get blocked
do u get that warning even without on_message event as well
like this regex code
then its likely some other part of the code blocking
Some one use "for" loop in the place of def then I got a doubt and i ask .
are u running some blocking tasks during startup
Put all the patterns into 1 regex and search that
oh that's not a function definition
that's just a for loop
they were talking about calling the function, not defining one
!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.
Ok now i understood 😁
https://paste.pythondiscord.com/5NCA I think it might be this
It also means the functions don't get called 900 times
Thanks for the help , sir 😂
npnp
You code in Java language ❓
a little bit
By seeing you Id i ask 😂
we should take it to #ot2-never-nester’s-nightmare then if we're gonna talk Java
oh "microsoft java" means C#
python >>>
rust >>>>>
@shrewd apex could it be this?
Ok , bro . I think that it's Java programming language
r.exists(key3) whats r?
This might still be quite a big issue
redis
isnt redis sync by default
I think it s a variable
u prolly want this
It is an python library
ok stop stating the obvious now 🗿
how?
wdym how?
❓
how do i use it?
read its docs
do I just install it?
pip install pypi
ok stop telling wrong stuff
oh I am
...
take a read
What I tell wrong ❓
whats pip?
It is use to download an library in python
whats pypi?
how to install library in python?
personal chatgpt
That's is library name.
pip install openai
PyPI is the Python Package Index at http://pypi.org/
!pypi pip
Python Package Index
it's like the play store of python libraries
in context of the installation 💀
Ok .
but exists 😄
sure
!pypi
package
!pypi <package>
Can also use: pack, package, pip
Provide information about a specific package from PyPI.
should send link to website imo
this guy is right
when i took the functions off it stopped blocking heartbeat
^
You can use "|".join for that
And maybe pre-generate the regex pattern too
no the functions are doing it
That's because you're running the functions 900 times, for each word
ohhh
💀
You could also run them once outside of the loop entirely
But you may as well optimize the regex too
could i do this
if re.search(pattern, replacedoublecharacters(replacespaces(replacespecialcharacters(sws)))), re.IGNORECASE) is not None:
That doesn't change how many times the function is run
Do it outside of the loop, or use a single regex for everything
!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.
ok ill try outside of loop
i get this error
when putting out of the for loop
when using this its not blocking the heartbeat
Code?
where can i find the json docs?
Source code: Lib/json/__init__.py
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript 1 ).
Warning
Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.
json exposes an API familiar to users of the standard library marshal and pickle modules.
Encoding basic Python object hierarchies:
yes, but for discord forgot the discord.py lol
i need to understand the json for discord.py
so i can save/send/read json files with the bot
i've done it, but in js
json works the same in each language
but what you wanna find in discord.py about json
how it works and like, everything about it lol
do you mean the discord API docs?
maybe yes, not sure about that
i don't really need error messages code...
to be more specific
i'm trying to do a command that if sent, give you a list of things, everything wrote on a json file
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**.
you pass file kwarg
yes
wait, read and send a json file
and maybe write lol
use open to open a file and then pass it to discord.File then pass it to file kwarg when sending
not understanding
reading and writing is just a python thing. you do it as usual
and for sending ^
ik, but i've done it years ago and i can't remember how i do that
!open
The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.
See also:
• !tags with for information on context managers
• !tags pathlib for an alternative way of opening files
• !tags seek for information on changing your position in a file
The file parameter
This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.
An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.
See !tags relative-path for more information on relative paths.
The mode parameter
This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.
'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)
alr
im looking for someone to make me code for a discord bot so all i have to do is input the token through a secret and add the hosting code
we dont code for you its a help channel we help you solve problems you face
😐
I can tell you’re a “Legendary coder/scripter”
Here is your bot:
TOKEN = "PUT YOUR TOKEN HERE"
print("IMAGINE A DISCORD BOT RUNNING")
whats the function for deleting the command trigger once a command is executed?
Average mountain Everest height attention seeking ego
In the end
can someone pls kod for mi
!d discord.ext.commands.Bot.remove_command
remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: `name` parameter is now positional-only.
im not looking to remove the command, im looking to delete the message that the user sends to trigger the command.
For example if a user runs /status, the bot sends an embed and delete the message the user sent
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
!D discord.Interaction.message
The message that sent this interaction.
This is only available for InteractionType.component interactions.
Is this an application command or a prefix command?
doesnt work
You need to drink i guess
Don’t use this to delete the message, calling raw methods on the message incurs rate limits. Take a look at interaction.delete_original_response() which is free of rate limits.
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
Do they have some different rate limits?
Read the bottom part of that
but we are not fetching message anyways
interaction.message.delete() fetches the message
Because your method won't work
interaction.message is not a fetch.
but it doesn't return a sent message
The actual method with getting message would be message = await interaction.original_response() + await message.delete()
sorted it now, it was a prefix command. I just implemented the ctx.channel.purge() function
Or just use delete_original_response()
It returns a message, and it’s not initially a fetch unless you call delete() or edit()
its a prefix command not an interaction command so i cant can i?
@bot.command()
async def status(ctx):
embed = discord.Embed(title=' Verde Status Check', description=f"**Server Count** | {format(len(bot.guilds), ',')}\n**User Count** | {format(len(bot.users), ',')}\n**Latency** | {bot.latency*1000:.2f} ms\n**Report Time** | {formatted_datetime}", color=discord.Color.brand_green())
await ctx.channel.purge(limit=1)
await ctx.send(embed=embed)
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
You can also do await ctx.message.delete()
why would you type it as elixir xd
ahh that would have been more simple 💀
bruh
the only code formatter i know for discord 😮💨
well this code is in python so why dont you use python lexer
Any language you can imagine actually exists in discord
i didn't know it existed lmao
there is even brainfuck for example
learn sum new everyday i suppose
terrible coloring tho
hi
actually.. idk how to color it better so..
def drive(%User{age: age}) when age >= 16 do
# Code that drives a car
end
drive(User.get("John Doe"))
wtf
interesting
HAI 1.2
I HAS A VAR_A ITZ 5
I HAS A VAR_B ITZ 10
VAR_A R SUM OF VAR_A AN VAR_B BTW 15
VAR_B R DIFF OF VAR_A AN VAR_B BTW 5
VAR_A R DIFF OF VAR_A AN VAR_B BTW 10
VISIBLE "VAR_A: " VAR_A
VISIBLE "VAR_B: " VAR_B
KTHXBYE
( anyways, ot)
lolcode lexer interesting
1c
4d
abnf
ada
what these languages even are
i is a language
hmm, or not
it is in the files
but not with the code block
#ЗагрузитьИзФайла ext_module.txt // директива 7.7
#Если Клиент ИЛИ НаКлиенте Тогда // инструкции препроцессора
&НаКлиентеНаСервереБезКонтекста // директивы компиляции
Функция ТолстыйКлиентОбычноеПриложение(Знач Параметр1 = Неопределено, // комментарий
Параметр2 = "", ПараметрN = 123.45, ПарамNN) Экспорт // еще комментарий
Попытка
Результат_Булевы_Значения = Новый Структура("П1, П2", Истина, Ложь, NULL, Неопределено);
Перейти ~МеткаGOTO; // комментарий
РезультатТаблицаДат = Новый ТаблицаЗначений;
РезультатТаблицаДат.Колонки.Добавить("Колонка1",
Новый ОписаниеТипов("Дата", , ,
Новый КвалификаторыДаты(ЧастиДаты.ДатаВремя));
НС = РезультатТаблицаДат.Добавить(); НС["Колонка1"] = '20170101120000');
Исключение
ОписаниеОшибки = ОписаниеОшибки(); // встроенная функция
Масс = Новый Массив; // встроенный тип
Для Каждого Значение Из Масс Цикл
Сообщить(Значение + Символы.ПС + "
|продолжение строки"); // продолжение многострочной строки
: )
i guess its normal language when translated xd
#LoadFromFile ext_module.txt
#If Client OR OnClient Then
&OnClientOnServerWithoutContext
function FatClientCommonApplication()
i am lazy for more
Hello, World!
============
Author Name, <author@domain.foo>
you can write text http://example.com[with links], optionally
using an explicit link:http://example.com[link prefix].
* single quotes around a phrase place 'emphasis'
** alternatively, you can put underlines around a phrase to add _emphasis_
* astericks around a phrase make the text *bold*
* pluses around a phrase make it +monospaced+
* `smart' quotes using a leading backtick and trailing single quote
** use two of each for double ``smart'' quotes
- escape characters are supported
- you can escape a quote inside emphasized text like 'here\'s johnny!'
term:: definition
another term:: another definition
``` this actually fire
ok we need to ask question about discord bots
how do i sync my slash commands in discord.py?
Use discord_slash and discord_components libraries
They are made specially for this
damn
Im trying to create a slots command but keep getting the same error.
Code:
@bot.tree.command(name='slots', description='Gamble on Slots')
@app_commands.describe(amount = 'amount')
async def slots(ctx:discord.Interaction, amount: int):
with open('userBalances.json', 'r') as f:
balances = json.load(f)
user_id = str(ctx.user.id)
user_balance = balances.get(user_id, 0)
if user_balance >= amount:
outcomes = ['✅','❌']
slot1 = random.choice[outcomes]
slot2 = random.choice[outcomes]
slot3 = random.choice[outcomes]
user_balance -= amount
if slot1 == slot2 and slot2 == slot3:
winning_amount = amount*2
embed = discord.Embed(title='Slot Machine', color=discord.Color.brand_green())
embed.add_field(name='**Result**', value=f'{slot1} | {slot2} | {slot3}', inline=False)
embed.add_field(name='You Win!', value=f'You bet {amount} Coins and won {winning_amount} Coins.', inline=False)
await ctx.response.send_message(embed=embed)
user_balance += winning_amount
balances[user_id] = user_balance
with open('userBalances.json', 'w') as f:
json.dump(balances, f, indent=4)
else:
embed = discord.Embed(title='Slot Machine', color=discord.Color.brand_red())
embed.add_field(name='**Result**', value=f'{slot1} | {slot2} | {slot3}', inline=False)
embed.add_field(name='You Lost!', value=f'You bet {amount} Coins and lost them.', inline=False)
await ctx.response.send_message(embed=embed)
else:
await ctx.response.send_message(f'{ctx.user.mention} you do not have enough Coins in your balance to make this bet.\nUse /balance to view how many Coins you have.')
Error:
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\jackf\Documents\Verde Discord Bot\main.py", line 868, in slots
slot1 = random.choice[outcomes]
TypeError: 'method' object is not subscriptable```
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError).
the issue im having is that a command on one of my other bots uses the same code yet this one doesn't work
its impossible it worked since the syntax is incorrect
see how to use random.choice
How can i edit a message that have been sent in async def test(ctx): from a class?
@bot.command()
async def test(ctx):
view = DropdownView()
requesting_message = await ctx.send(embed=embed, view=view)
await asyncio.sleep(1)
await requesting_message.edit(embed=embed2)
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="Database-Staff", description="Database dello Staff"),
discord.SelectOption(label="Database-Car", description="Database Auto"),
]
super().__init__(placeholder="Seleziona un Database", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "Database-Staff":
await interaction.response.send_message(f"{self.values[0]}")
elif self.values[0] == "Database-Car":
await interaction.response.send_message(embed=discord.Embed.from_dict(embed_dict), ephemeral=False)
Just to make sure you understand, i have this and after the Dropdown is selected, the message have to be changed. ;-;
nvm
Hey there! I know Discord.py was making a return, previously I was using Disnake, as well as many others. My question: what is the current most feature rich / best supported / best implementation of Discord in Python?
I think it's personal choice tbh. Seems like disnake is more user friendly on the dev side from what I've heard, but I've never used it just discord.py
i pressed once
Do you have a response to the interaction?
do i really need it?
If you have no interaction.response then it'll say failed every time.
but what if i don't really want to send a message?
You could make it send an ephemeral message if you don't want something everyone can see
even if it's ephemeral=False
ik that, but what if i don't want the bot to send something
haven't tried to get around that myself. I like to have a positive indication something is happening
You could interaction.response.edit_message and just disable the button that was hit
can't, it's a button to change page
it works with the await interaction.response.defer()
Ok
just have to do some changes and it should be fine, ty
defer() is usually the preferred way
I am trying to create a custom embed command that people can use with adminastrator roles. I am very confused while doing this and I would like help if anyone can help me.
What I'm trying to do with the custom embed:
Allow the user to add a title, descriptoin, image, footer AND a button
So if anyone knows how to do this please reply or mention me.
Depends on how you want to do it
With prefixed commands, slash commands or modals?
Or dropdowns
Do you want to do it in multiple messages or just one?
i would like to do slash commands like it would have options to input what you would like, sir.
just one will be ok
I'm just confused on how to do this as a whole thats why I came here
Would you be able to help me with this
Well you would just have them as args in your slash command
Set certain ones as optional, others as required
i want it to look like this
and in the slash command u can set the custom embed to send to a specific channel and everything
Oh, so it's not a dynamic generator? An administrator sets the format, and that get saved?
Do you have any code so far?
i mean i had coded one for a prefix, but i want it as a slash command and im not good with those
so no i do not
I would recommend learning how to use slash commands first
Here's a basic example
how did you do that stuff
it will look like this /embed (channel: [value]), (title: [value]), (description: [value]), (footer: [value])
ill look thanks
async def join(interaction: Interaction):
"""Join the voice channel the user is in"""
if interaction.user.voice:
channel = interaction.user.voice.channel
await channel.connect()
else:
await interaction.response.send_message("not in a voice channel")```
why does this always provide '``not in a voice channel``' even when im in one?
This would be extremely easy to do. Just setup the args for each input in your function, then save it in a database. When you need the settings, you’d pull it from the database and create the embed with the information
Does your bot have the intents/permissions required?
yesh
intents.typing = True
intents.presences = True
client = discord.Client(intents=intents)```
@toxic moat Do you have any code so far for your command?
I might in a bit i am looking at that link robin sent me
if os.path.exists("config/payment.png") :
file = discord.File("config/payment.png", filename = "payment.png")
embed.set_image(url = "attachment://config/payment.png")
await ctx.respond(file = file, embed = embed)
completly honest i might need a little like explanation on what this is supposed to make click
Are you sure your bot has the permissions to view the channel? Could you print voice for me?
it has admin perms
And you're running the command in a guild?
attachment:// are according to your discord.File.filename since they reference within the same message attachment, they don't have anything to do with your filepath, it should just be attachment://payment.png to reference the image
tbh i dont have anything cus thats in cogs
the file is didn't appear when i executed the command (rn)
please read on what i said
@golden portal could you give me a syntax pls ?
file = discord.File("config/payment.png", filename="payment.png")
embed.set_image(url="attachment://payment.png")
await ctx.respond(file=file, embed=embed)
the error however i dont know since i dont use that fork
not working :/
yea i dont really use that lib
I don’t see any reason why it shouldn’t
oh no problem 🫂
thanks for help
@final iron could you help with that case 🙂 ?
Aside from the bot not being able to see the channel, (it could have user specific permissions) I don’t know why it wouldn’t be able to get your voice state
ctx.respond?
is that a d.py fork or smth?
welp that's what i been saying for a while
Prob
or is that actaully smth
yea they are using another fork
oh ok
Show me the user specific perms/role specific perms for that channel
Humour me
i've been tryna figure this out on like 5 different severs, tons of different VC's
What version is discord.py
@bot.event
async def on_message(message):
if message.author == bot.user:
return
content = message.content.lower()
author_highest_role = message.author.top_role
bot_highest_role = message.guild.me.top_role
if bot_highest_role < author_highest_role:
if any(word in content for word in FILTERED_WORDS):
await message.delete()
await message.channel.send(f"{message.author.mention}, that's not allowed!")```
**Why doesn't this work I get no error in the terminal.**
what happens?
litteraly nothing happens the bot does not delete the message, and does not say anything after they sent one of the filter words
Do you have logging? do you have the message content intent?
no logging, and yes
why do you not have logging? are you using bot.start?
bot.run
positive
Show the intent in your code, and it being enabled in the dev portal
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
property top_role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
i have everything enabled
discord 2.3.1
discord.py 2.3.1
mb for late i took a shower
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.
its literally an entire discord bot
How many lines?
400-500ish
theres a python pastebin yk right
. he just showed it to me
Is your role higher in the hierarchy than your bots?
but it's 400-500 lines and i don't think it's very convenient to just paste 400-500 lines and say "yeah read the whole thing"
okay
I honestly find your situation pretty strange
Humor me, see if it works if you set your intents to all
is this not against discord terms of use?
by what?
iplookup
oh okay
so nu uh
Might be some weird slash command interactions
What if you get() the user object and see if it says it's connected?
Just as a temporary measure
um what
it doesn't detect that i'm in a VC at all, if i saw i was connected but couldn't transfer it to connection it would raise a different error
what
What does that have to do with what I said
get() the discord.Member object and see if it says it's in a voice channel
@toxic moat
? i tested the bot with my alt and the bot is higher than my bot
yep
!e
print(1 < 2)
@final iron :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
wha-
Example for him
Right now you're checking if the authors highest role is higher than the bots
You just told me that's not true
so how do i fix it..?!
...
Just flip the symbol...
Why do you have that there in the first place, what are you trying to acomplish with it
I want to know the internal working of bot.load_extension?
bot.load_extension loads exts
discord/ext/commands/bot.py line 962
async def load_extension(self, name: str, *, package: Optional[str] = None) -> None:```
feel free to read the source code if you want to
thanks for this I wan't able to find this in source code
idk how because i found it pretty easily
btw is it possible to implement this in another python project?
copy and paste code from dpy?
lol
yeah kind of
learn and copypasta
sure but i would recommend reading the code through and understanding it before you use it
yeah I'll : )
ok
is there any way to hide a slash command for everyone except for specified User IDs or check if user is owner
from discord.ext import commands, tasks
import asyncio
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
# Initialize bot with command prefix '!'
bot = commands.Bot(command_prefix='!', intents=intents)
BOT_PREFIX = '!'
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} - {bot.user.id}')
print('------')
watching_activity = discord.Activity(type=discord.ActivityType.watching, name="over AutoShop")
await bot.change_presence(activity=watching_activity)
@bot.command()
async def purchase(ctx):
# Replace these placeholders with your actual PayPal and crypto wallet addresses
paypal_address = "**[PayPal](https://www.paypal.me/erfanproguy2)**"
bitcoin_wallet = '**bc1q5cf7v6lr7yrtdferlqq07hqww7wqw8dfwp5a66**'
litecoin_wallet = '**Laf9AR7LdtrpkrTgFkx5RVci65ngxViTqa**'
ethereum_wallet = '**0x3f74a98bA3468e25F9cFc02852BF7883B4D707e9**'
embed = discord.Embed(title="Purchase Information", description="Here are the following purchase options:", color=0x00ff00)
embed.add_field(name=" Paypal", value=paypal_address, inline=False)
embed.add_field(name=" Bitcoin Wallet", value=bitcoin_wallet, inline=False)
embed.add_field(name=" Litecoin Wallet", value=litecoin_wallet, inline=False)
embed.add_field(name=" Ethereum Wallet", value=ethereum_wallet, inline=False)
await ctx.send(embed=embed)
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
# Respond with the bot's prefix
await message.channel.send(f"My prefix is `{BOT_PREFIX}`")
bot.run('')```
**Why is none of this working..** # no errors btw
@final iron
sooo.... idk why its marking it, but it is... and i dont see any error...
class CreateSelect(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
custom_id="ticketopen",
options=[
discord.SelectOption(label="What is Sampler", emoji="✨"),
discord.SelectOption(label="Guide to AI Models", emoji="📚"),
],
)```
it says this
added await bot.process_commands(message)
doesnt help at all
Where did you put it?
I hope it's not in the if-statement
async def on_message(message):
if bot.user.mentioned_in(message):
# Respond with the bot's prefix
await message.channel.send(f"My prefix is `{BOT_PREFIX}`")
await bot.process_commands(message)```
Move it out of the if-statement
oh yea 
Is it possible to receive a slash command message ID before a message is sent? I'm trying to make sure the purge command I have doesn't delete the original invoking of the command before it responds.
it goes in this order: Invoke -> Purges Messages -> Says how many deleted msgs


