#discord-bots
1 messages · Page 250 of 1
Discord moment
!zen 1
Explicit is better than implicit.
yes because there are no roles in dms, hence has_any_role always fails
Imagine code linter that would check zen compliance: ||ZEN0: your code is too ugly||
lmaoo
!zen someone needs to make this
Namespaces are one honking great idea -- let's do more of those!
!zen
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
i already told you how to fix the error
This is approximately 4006th ohh in this channel
cool fact
having a verified bot without message content means no more ctx.command?
The command is either not invoked at all, or if the bot was pinged it works and Context.command is accessible
so the bot can read messages where it was mentioned?
Yeah
okok
no
Hello, does anyone use goormide? I have a question.
Seems like you should go to #editors-ides
@slate swan
If anybody has some time i would apreciate if you take a look and help me.
Problem:
So i make a code for dropping some character images in a embed (this works perfectly fine) and i wanted to add a way to collect them so i made a way to collect them by adding a reaction and it will go to the inventory that is stored in a json file ( there where problems begun) so lets specify them.
When i add a reaction under the embed bot does not send a message that is supposed to send.
no character is added to collection nor the json file but the !collection command is working okay bcs it respods with no characters collected yet it is okey.
i added some prints to help me find the issue but since i am a noob i just cant find a problem
termial print:
Reaction added!
reaction: 🎉
user: Valheru#8645
self.client.user: (bot name here) it is here but i just dont want to shere the name of it
message.author: (bot name here)
embeds: [<discord.embeds.Embed object at 0x000001531E9E2F80>]
embed: <discord.embeds.Embed object at 0x000001531E9E2F80>
bot code --> https://paste.pythondiscord.com/awunuvawid ( dont pay attention to the hiragana i was making bot for japaneese learning)
cog --> (feature is here) https://paste.pythondiscord.com/udulucuwiv
changing status every 5 seconds 
Nvm
Is it something like the Pokemon bot
I couldn't see your code but you should call unban on an instance instead of the class
I don't even know how defining self like that works but ok
class is blueprint or template for creating objects, while an instance is a specific object created from a class
its when you assign a variable to a class that it becomes an object of a class
client = Client()
@slate swan watch https://www.youtube.com/watch?v=JeznW_7DlB0
class Car:
# Class attribute
wheels = 4
def __init__(self, make, model):
# Instance attributes
self.make = make
self.model = model
def drive(self):
print(f"Driving the {self.make} {self.model}")
# Creating instances of Car class
my_car = Car("Toyota", "Camry")
your_car = Car("Honda", "Accord")
# Accessing class attribute
print(Car.wheels) # Output: 4
# Accessing instance attributes
print(my_car.make) # Output: Toyota
print(your_car.make) # Output: Honda
# Calling instance method
my_car.drive() # Output: Driving the Toyota Camry
your_car.drive() # Output: Driving the Honda Accord
In this beginner object oriented programming tutorial I will be covering everything you need to know about classes, objects and OOP in python. This tutorial is designed for beginner python programmers and will give you a strong foundation in object oriented principles.
◾◾◾◾◾
💻 Enroll in The Fundamentals of Programming w/ Python
https://tech-wi...
🥴
lmao
ModuleNotFoundError: No module named 'discord.commands'
it’s discord.ext.commands
im getting this error now ImportError: cannot import name 'commands' from 'discord.ext.commands'
Gays how can I change the activity for my bot
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.all()
client = MyClient(intents=intents)
!d discordpy.discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
more like mudae ig i mean you add reaction and you collect it but apparently it just a picture sending simulator XDDD
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
look at the example
could that be because "TOKEN" is not your actual token
I put it as a secret
os.getenv(key, default=None)```
Return the value of the environment variable *key* as a string if it exists, or *default* if it doesn’t. *key* is a string. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): Unix, Windows.
w3schools 
So I've been developing a way to develop discord bots in a way like BDFD and Aoi.JS, just in python! So if anyone wants to check that out feel free! It's still very much in alpha and isn't meant to support a public bot yet-
https://github.com/LilbabxJJ-1/AoiPy
lol
XD
huh, i havent seen "string-based" discord bot libraries before
I wonder what the target audience would be
what is a string-based package
I don't know why but dpy is still feeling easy
yeah just do toml or json files
Commands are literally string based (Mainly targeted at beginners and people who don't know much programming)
example of a command in the given package is
bot.command(
Name='sayName',
Code="""
$argCheck[1;You need at least 1 argument!]
$sendMessage[$channelID;Hey $args[1] and $userMention[$authorID], this message is in $channelName[$channelID]]
$wait[5]
$sendMessage[$channelID;This is my finally message!! Bye $args[1] and $userMention[$authorID]]
"""
)
Not meant for people who already got d.py down in the bag xD
But can be used
that looks even harder than python
why would you want to learn a new DSL/language just for making a discord bot when you can just learn python
Because the self proclaimed discord bot developers in this channel are never going to learn python
it's mainly just an alternative to people who don't know how to program. Making most of the commands into plain keywords and stuff
so keywords like $channelID to return the channel id may seem unnecessary to people who already know programming but it simplifies it to anyone who doesn't
you could still simplify the syntax a lot ```
if args.length < 1
sendMessage "You need at least one argument!"
stop
sendMessage "Hey $args[1] and $author.mention, this message is in $channel.name"
wait 5
sendMessage "This is my final message! Bye $args[1] and $author.mention"
should just integrate with blockly
Oh?
would be a lot more user-friendly
Looks like you're using tasks.loop just to poll a queue every second. Instead, you can try using any asyncio Queue, which you can await for new items in the queue.
You shouldn't be using a task loop to handle your enqueuing logic at all; VoiceClient.play has an after kwarg that takes a callable which is called when the audio source is exhausted
Err listen to that person ^ I'm not familiar with the voice client specifically
This may be a very stupid question, but I feel like I'm missing something here
I just installed discord.py, so I'm on the latest version
I've got a very minimal bot here, which only prints "We are logged in" once on_ready() is fired
for some reason, it errors before even reaching that point, with the following code
import discord
import events.onready
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
@client.event()
async def on_ready():
onready.on_ready()
client.run("<bot_token>")
However, this for some reasons errors out with
TypeError: Client.event() missing 1 required positional argument: 'coro'
Where the heck is this from?
Am I missing something obvious here?
i need
help
i want the command which can help me save the ticket transcript when emoji is selected
how am i suppose to do hat
As per documentation, it's @client.event and not @client.event()
could you help me/
sigh
Thank you, I figured it was something simple like that
You'd think after using python for 8+ years, I'd realize issues like that by now
Can happen 
This is a replicate of that mobile app people use for bots
I did say that It was similar to BDFD and Aoi.Js @slate swan
how do i do prefix commands
create a commands.Bot first
then use something like ```py
@bot.command(description="Says hello to someone.")
async def hello(ctx: commands.Context, user: discord.User = None) -> None
if user is None:
await ctx.reply(f"Hello, {ctx.author.mention}!")
else:
await ctx.reply(f"{ctx.author.mention} said hello to {user.mention}!")
you would use the discord.ext.commands.command decorator in a cog instead
how can I access any dms the bot receives?
Use the on_message event and check if the message.channel is an instance of discord.DMChannel, then you know the message was received from DMs
getting this error
Yes, you've already sent it a few seconds before and as mentioned the error says it all, no password supplied - also that port seems to be postgresql so #databases
best app to coding
Here again, wrong channel -> #editors-ides
bruh
ty
how make imge in embed link
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing `None` removes the thumbnail.
Depends if you want a thumbnail, top right, or an image in the embed
how to make economy features
There are dozens of economy features possible, think about what you really want instead of asking random questions for the past minutes
need cordes
To make economy features you will likely need a database and then have commands that interact with that database
Sorry to disappoint you, we don't spoon-feed with code
You code, we help with issues you face
i install postgrsql it's need host, username, port, database how can i get these pls tell expert
As said, ask in #databases and wait. I'm also not an expert whatsoever
no one reply there
All right, let me send it again
As said, ask in #databases and wait.
So create post in #1035199133436354600 or just search the internet
It's very mind blowing but in life you don't get everything in the second you ask for it
file = discord.File("path/to/my/image.png", filename="image.png")
embed = discord.Embed()
embed.set_image(url="attachment://image.png")
await channel.send(file=file, embed=embed)
my await... embed) coming on red line where to type it await channel.send(file=file, embed=embed)
Show the error not what displays on red in ide
am trying to creat form month for economy feature
see
That's not the error
That's also not the error
And the error is pretty obvious though
That's code
You cannot send a message randomly like that
Send the error and i will show you its self explainatory
That's why commands and events exist
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
await channel.send(file=file, embed=embed)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
Then your error is, as the traceback will confirm, that you cannot use await outside of a function
this is coming
See its telling you
There we go
That you cant use await outisde async function
so what to do
move it inside an async function
how
async def (and then)?
welp u see the commands
there is an async function first that explains when the command is triggered
so you need to do something similar with this
what
can you giv
when u want the the bot to send the message and the file??
image in embed link
@bot.commands()
async def test(ctx):
embed= discord.Embed(title='...', description='...')
embed.set_image(url=...)
await ctx.send(embed=embed)```
in title in can past image?
show me what did you do
see
!indents
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
The first thing you learn when learning Python
my bad i forgot the indents while sending the example
and the way you are putting in the image is wrong
oh
it should be like
embed.set_image(url="attachment://filename.png")
hep red line come to await
@bot.commands()
async def test(ctx):
embed= discord.Embed(title='...', description='...')
embed.set_image(url=...)
await ctx.send(embed=embed)```
like this
C:\Users\M I S COMPUTER\Desktop\bot>py bot.py
File "C:\Users\M I S COMPUTER\Desktop\bot\bot.py", line 28
embed.set_image(url="C:\Users\M I S COMPUTER\Desktop\bot\SachinTendulkarMain.png")
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
hey wha't this
i told you you are using wrong way to add image
it should be like
embed.set_image(url="attachment://filename.png")
if the file is in same folder as main.py file
if its in a subfolder then it should be like
embed.set_image(url="attachment://folder_name/filename.png")
lik this
embed.set_image(url="bot.py://C:\Users\M I S COMPUTER\Desktop\bot\SachinTendulkarMain.png")
what attachment
like this
attachment is basically telling it that you are to send a local file instead of a link
oh what was of cmd run bot
async def print (log in as {user id}
?pls tell full code
bot.run('Your_Bot_Token')
refer to this -> https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
it's easier that way
File "C:\Users\M I S COMPUTER\Desktop\bot\bot.py", line 18, in <module>
@bot.commands()
^^^^^^^^^^^^^^
TypeError: 'set' object is not callable
no s for command
done
wait did Rapptz remove the autosharding example? o.o
Never seen someone call Danny "Rapptz" 
;-;
Probably removed because there's no real necessity
It's just changing one class name
bot stop working
You can typehint the interaction argument of command callbacks as disnake.GuildCommandInteraction
Example: ```py
@bot.slash_command()
async def example(inter: disnake.GuildCommandInteraction):
# this command won't be visible in DMs
...
Okay nice

Plus it will make it easier to code, since linters will know that inter.guild is not None, as well as inter.author is disnake.Member
Etc.
my bot not sending
what to be the code
@bot.command() async def buy(ctx): embed= discord.Embed(title='...', description='...') embed.set_image(url="SachinTendulkarMain.png") await ctx.send(embed=embed)
Sometimes in my bot, idk how but when i try to interact with a button it says interaction failed and i have to write again !ticket. Is there any way to fix it?
It also happens when i restart the bot
thats smart thing in disnake
hi sir owner
SachinTendulkarMain.png is not the url
do you still need the decorator?
i thought the special guild contexts/interaction objects are only for type checking purposes

sigh I already told you the functionality of some of disnake.Interaction's subclasses
lol hi
Nope, only the typehint
In disnake typehints often handle some logic
is that the owner of disnake
yes

oh
promoting his own library !1!1!
me still using nextcord for my projects: 
me using disnake and forcing snipy to write everything
nah bro, nextcord doesn't support the file kwarg on send methods
you should be grateful
!d nextcord.ext.commands.Context.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` or `embeds` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.File "nextcord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.File "nextcord.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://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed "nextcord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Embed "nextcord.Embed") objects. **Specifying both parameters will lead to an exception**.
mmm maybe it was for embeds
still it's not supported everywhere
see interactions
I'm pretty sure since I made a pr for that
no
i see
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
wait let me try to troubleshoot i might be able to fix it
hm that's weird, i don't see why it would point to the ', part specifically
ah fixed it
Did you know that windows (yes) also works with / 
You can clean up some of your code now :)
i've only ever used / really

#I tried to make my bot stay online by using a while loop that runs the token forever but
Working = False
Code = "https://paste.pythondiscord.com/nulucexuzo"
Error_message = Image Below
your token is not correct
also i'm pretty sure that while loop won't work
just use await client.close() where you need to stop the bot
I was gonna say i had just copied the token but I realized I copied the client secret not the bot token
Thanks, it worked now
So im trying to have it to where the location(a vc) of the user who sent the command linked and clickable. the first part of it works just not the other part. i hope this makes sense. the error is in the picture
code:
chicken.add_field(name=f'**{interaction.user.voice.channel.name}**', value=f'[Click here to join] **{interaction.user.voice.channel.connect()}** ', inline=False)
interaction.user.voice is none
how can i create my own discord chatbot ai with custom knowledge? are there any projects?
can u elaborate pls
Yes there most likely are with that cringe AI overhype going around, just use a search engine and you'll most likely find a dozen
is langchain good?
Don't know, ask google
ok thanks i didnt understand it first
do you want to pay or do you want to use an open-source model
await channel.send(f"{message}")
AttributeError: 'int' object has no attribute 'send'```
@client.tree.command(name="welcome-setup", description="sets up a welcome system")
@app_commands.default_permissions(manage_guild=True)
async def welcome_setup(interaction: discord.Interaction, channel: discord.TextChannel, *, welcome_message: str):
db[f"channelname {str(interaction.guild.id)}"] = channel.name
db[f"channelid {str(interaction.guild.id)}"] = channel.id
db[f"message {str(interaction.guild.id)}"] = welcome_message
await interaction.response.send_message("Welcome system setup")
@client.event
async def on_member_join(member):
channel = db[f"channelname {str(member.guild.id)}"]
channel = db[f"channelid {str(member.guild.id)}"]
message = db[f"message {str(member.guild.id)}"]
await channel.send(f"{message}")
im making a welcome system but its not working
i get this error when someone joins
you define channel twice and it ends up being an int
oh
Open source would be better for the beginning
@client.event
async def on_member_remove(member):
channel = db[f"channelid {str(member.guild.id)}"]
message = db[f"message {str(member.guild.id)}"]
await channel.send(f"{message}")
await coro(*args, **kwargs)
File "main.py", line 67, in on_member_remove
await channel.send(f"{message}")
AttributeError: 'int' object has no attribute 'send'
now channel is not defiened twice
why is it not working

oh
What’s this
Your bot is rate limited 🫠
How can I fix this?
channel1 = db[f"lchannelid {str(member.guild.id)}"]
channel = client.get_channel(channel1)```
can i do it like that
it works but how do i mention the member
member.mention
What did u even do to get rate limited??
Idk maybe my host is not good
blud is trying to nuke somone or smth like that
No
Or might be a purge command?
I have no commands I have only a links block system.
myb provide us the code?
without token
Yup will need to see the code to figure out the problem
Cuz even if u are blocking links it's not like there 50+ links being uploaded every second that the bot is trying to block
@uncut lynx ein rate limit tritt nur auf wenn der bot zu viele aktionen in kurzer zeit durchführt
und eine art timeout bekommt
ja
schick einfach mal den code rein
Oh nicht der ganze Code
looking for a developer dm me
Hat sich glaube ich wieder erledigt
Der Fehler kommt nicht mehr
The more people looking at a code the better chance to find an error
Hello! I cannot figure out how to remove embeds from user's message.
When user posts link discord automatically shows preview of this link. It is sometimes annoying so i want to remove these created embeds using bot. How can i do that?
I tried several things, but none of them worked (some did nothing, some raised 403)
Lib/_py_abc.py line 14
class ABCMeta(type):```
for example, this bot automatically removed embed from my link
Use .edit(suppress=True) on the message object you want to remove them from
it works 👍
i thought it is not possible to edit other's message
It's a bit misleading yeah, it'd be better with a separate function with some different name
But technically you are editing their message, it's one of the only things you can do
i need a developer for a discord bot just to update some code will pay nitro dm me
don't ask for paid work here
As already said just ask for help here or create a thread
where can i create a thread
@smoky sinew
Hey i keep getting this error what should i do , im new to python.
show test function definition
how "new" are you to python?
today
i got it to work
but im getting a new error
Unfortunate
new error always means progress :)
yeah.
place for commissions
@austere pewter
Is ur user object a user object or a member object?
its a banned member and im the owner
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I believe its ur type hint.
You hint the user as a member instead of a user.
A member means a guild member, but there is no member here, as the user was banned.
ohhh
Fixed?
Yes! thank you
Oh , one more thing
what do i look up to have more commands?
like
@austere pewter
Yessir.
Wdym more commands?
Well, you could access the guild object, and find information about it.
what am i doing wrong
reset your token
you just leaked it, you're not supposed to share it
also the issue is you need to enable the message content intent in your bot page:
https://discord.com/developers/applications
And enable privileged intents from developer portal
That's what the error u got saying
thanks did not know
yes your token is what allows someone to log into your bot
And some nasty things can happen if it's leaked
i try and do the command and it does not work
are you using chatgpt?
yea
that's your problem
it's trying to tell you how to make commands in the terminal, not within a discord bot
look here instead
Tbh we already told u why u were getting your error earlier
how do i make it so the discord bot does not say the same thing twice when you put the command in
Wdym it is double replying?
Yes
Can u send the code?
And yeah make sure u are not running the code in two places at same time
I think I over lapped it, it did say something but then I clicked on it then it started to over lap
Remove the lap and restart bot
How do I remove it
Just close the bot in one of the terminals
Is it possible to make the bot run many tasks in the background after a command is used?
Yes, as long as something isn't blocking
Hey, question again, this time regarding reactions
I'm trying to get when a user reacts to a message, and I've tried both on_reaction_add and on_raw_reaction_add
both give me an object that I can work with, and recognize the reaction
However, I need a way to get the string representation, that isn't unicode
For example, if someone uses 🗞️, I don't want the unicode of that, I want newspaper2 as a string
Is there a way to get this?
I can't seem to figure it out in the docs at all for built-in emojis, only custom ones
I don't believe there's a way to natively get that because the emoji set is a Discord/Twitter thing
crap, alright...
So unless I feel like making a unicode->string conversion function, and hardcode them in, it's going to be annoying?
Most likely is some library out there existing that maps them though
You're probably not the first one wanting that, so search a bit and you'll likely find something
discord uses twemoji for the default emoji, so there's a library for it yea
Or yeah if you want, map them yourself 
I've been trying to keep this project as few dependencies as possible, but might need to add a second one heh
Because Unicode is a pain to deal with in code, and I need to check if I have a specific emoji being reacted
Can't you do something like reaction.emoji == "😳"
The first one seems like a you issue, it's not really pain.
Second one is possible with unicode as well
I remember doing something like that 🐈
But what do I use for that?
I'm attempting to avoid Unicode at all if I can
I have my reasons for it, but it's not something I'm willing to budge on sadly...
Make alot of different discord.ext.tasks? Or build my own with a tasks module?
Then get a library, or if you're that crazy about having the least dependencies possible, map them yourself one by one
okay but first of all, one emoji does not map to one names
second of all, twitter did not name the emojis, discord did
it's really not
you can just use \u1F44D instead of 👍 for example
or the other way around, whichever you want
unicode being a pain is a side-effect of me coding in vim and using terminal for everything
it's annoying to make work most of the time
I want to learn every discord python code from where should I learn?
the docs
?
are there examples of hybrid_command() and @hybrid_group()?
and should i use them or app_commands? 🤔
Creating hybrid commands works the same as old prefix commands
If you want to allow prefix commands and slash commands, use them - otherwise just use the normal app commands
Server [localhost]: Best to share a minimal repeatable example.
Database [postgres]:
Port [5432]: Also do you have psql on your Terminal
Username [postgres]:
psql: warning: extra command-line argument "a" ignored
psql: warning: extra command-line argument "minimal" ignored
psql: warning: extra command-line argument "repeatable" ignored
psql: warning: extra command-line argument "example." ignored
psql: warning: extra command-line argument "-U" ignored
psql: warning: extra command-line argument "postgres" ignored
psql: warning: extra command-line argument "-d" ignored
psql: warning: extra command-line argument "postgres" ignored
psql: warning: extra command-line argument "-p" ignored
psql: warning: extra command-line argument "Also" ignored
psql: warning: extra command-line argument "do" ignored
psql: warning: extra command-line argument "you" ignored
psql: warning: extra command-line argument "have" ignored
psql: warning: extra command-line argument "psql" ignored
psql: warning: extra command-line argument "on" ignored
psql: warning: extra command-line argument "your" ignored
psql: warning: extra command-line argument "Terminal" ignored
psql: error: could not translate host name "Best" to address: Unknown host
Press any key to continue . . .
i got this error
It may be time for you to stop sending here database related questions, there's #databases for a reason
I want to make the bot give the role to the person after they bump the server,How will i make that happen?
I have thought of a idea where the Fibo(bump reminder bot) sends a message after they bump the server and that bot pings someone after they bump
"Thx for bumping our Server! We will remind you in 2 hours! @user"
How will i get the usrrname and tag of the user and give them the role?
what's the command to bump
you can just listen to messages for a message like !bump
if it's a slash command it's a little more complicated but i think you can do that too
its /bump
Yes it is slash command. thats why i dont know how to do it
i have thought of doing this @smoky sinew
sorry for many pings
you can do that
i am asking how to do it...
i looked it up but still cant understand it
this is my code for now
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("Thx for bumping our Server! We will"):
Last = message.content[57:-1]
The "Last" variable gets the "@user" btw
you have to install it
and using replit is not recommended; #965291480992321536 message
what i have to install
Is there a way to open imessage instantly from discord via a link?
i'm assuming you did not mean to paste "Best to share a minimal repeatable example"?
Yeah I use this before. What question do you have?
do pip install discord in the shell
do pip install discord.py
discord is a mirror of discord.py
!pypi di scord
!pypi discord
A mirror package for discord.py. Please install that instead.
try console: pip install discord
if discord is download,
pip uninstall discord and try pip install discord
!pypi discord
A mirror package for discord.py. Please install that instead.
"guild" is not defined
send code
!e ```py
print(guild)
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(guild)
004 | ^^^^^
005 | NameError: name 'guild' is not defined
you need to define varriable guild to be able to use it
sooo... i got this eror:
the cmd is an image re-generation cm which re-generates an image off the same prompt as before
as its telling you, there is no such thing like interaction in discord module maybe you want Interaction ?
done.. same error
show it
getting error in discord python project
it's in REPLIT
I can give invite link
Just show the error
It seems there is some error with the a file json file you trying to access
config.json
its totally fine
Sry can't help with that u need to wait for someone who has been working that
show 20 line of the json file that you are trying to open
ok
@slate swan
values must be separated by ,
That's pretty obvious
That was done before
but then i get a different type of error
then show the other error
No
That would give you an error if it's the last one
also json supports boolean type so you can do "premium": true
Nah it isnt
no
!e
import json
string = """{
"name": "Blah blah blah",
"age": 0,
}"""
print(json.loads(string))
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 8, in <module>
003 | print(json.loads(string))
004 | ^^^^^^^^^^^^^^^^^^
005 | File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
006 | return _default_decoder.decode(s)
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
009 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/json/decoder.py", line 353, in raw_decode
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/oxiwokuseq.txt?noredirect
@slate swan working now tq
👍
hey can u help me out with this
I'm getting this on console
but actaully it had to come out at ALEX BOT ENTER TOKEN
self bot 
self bots are not allowed so i cant
flex ( it's only print )
No it's a bot
not a sb
bruh it's only print
why would you print that then
I only need to print it and show it working in console
Why would you need to print that if it's not a selfbot
Not really
why?
I'm putting it on console cuz if i add it on normal code it'll get leaked
Why would you need to input token every time when starting
Because REPLIT isn't 24/7?
what does that have to being 24/7
and if i add it on normal code it'll be leaked
Environment variable exists for a reason
Eh, I probably can't say anything anymore
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
doesn't replit have something called variable key or something like that in the panel
u can store the token there
That's the environment variable
yeah and replit has inbuilt env which u can use and nobody can access it accept you
i'll jusut remove it?
That's pretty much what my message says
this happened
when i remove the bot=true
yes
i remove the bot=true here
is there a way to get cooldown data like say for example a user used the command and is on cooldown can i get a list of users which are on cooldown?
The error says otherwise, your token isn't valid
no unless you store this data by yourself
sed
mhm
maybe try resetting your token and put a new one? https://discord.com/developers/applications
I think that you can surely use some internal attribute to achieve that https://github.com/DisnakeDev/disnake/blob/stable/disnake/ext/commands/core.py#L881-L903
but I'm not too sure
Is there anyway to like host a bot in termux? Like using a webserver or something
yeah i have to look into buckets impl thing is i want to make a reminder task loop when cooldown ends
think ill just record the usages ig
yeah I think it would be simpler
I mean, it has to be stored somewhere
hmm
CooldownMapping._cache
nextcord/ext/commands/core.py lines 836 to 844
def _prepare_cooldowns(self, ctx: Context) -> None:
if self._buckets.valid:
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
bucket = self._buckets.get_bucket(ctx.message, current)
if bucket is not None:
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore```
this is the only place where its raising the error
it is the same for dpy and nextcord?
yes
pretty sure
prefixed commands should be the same
and cooldowns are only for those
That's called source code navigation I think
I mean if you just click something gh might find it
Won't give you source of external libs but repo code sure
yhyh
bruh ?
Traceback (most recent call last):
File "F:\mesdraps\ecp\main.py", line 27, in <module>
class selector(discord.ui.View):
File "F:\mesdraps\ecp\main.py", line 33, in selector
@discord.ui.button(label = "", emoji = ":brush:", style = discord.ButtonStyle.grey)
AttributeError: 'function' object has no attribute 'ui'
!paste can you paste your whole code?
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
class selector(discord.ui.View):
@discord.ui.button(label = "", emoji = ":discord:", style = discord.ButtonStyle.grey)
async def discord(self, button, interaction):
rolee = interaction.guild.get_role(1115740670821404753)
button.disabled = True
return await interaction.user.add_roles(rolee)
@discord.ui.button(label = "", emoji = ":brush:", style = discord.ButtonStyle.grey)
async def gfx(self, button, interaction):
rolee = interaction.guild.get_role(1116769003558416467)
button.disabled = True
return await interaction.user.add_roles(rolee)
@bot.command()
async def selector(ctx) :
await ctx.channel.purge(limit = 1)
embed = discord.Embed(title = "",
description = "**Select the right accesses in the selector below !**",
color = 0x2f3136)
await ctx.send(embed = embed, view = selector())
@sick birch
nah there is the modules on the top and the bot.run
Can you paste everything?
naming your function discord 💀
If you have a function and a class named the same, you're confusing python hence your error
Then yeah, naming a function discord while it's used for the imports is also not really ideal as it'll also overwrite it
Naming conventions ask you to name your classes to start with an uppercase, unlike functions
And find a better name for the discord function
Hello do you know how to create a ballsdex bot? A tutorial, a code, or something like that
by the way label="" and style=discord.ButtonStyle.grey are the defaults
yeah ik i just add them to edit them in the future quickly
how can i remove this error when someone clicks ?
like the bot gives the role to the member but without displaying this error
respond to the interaction
yeah which one
i don't want to respond another embed
or something like that
¯_(ツ)_/¯
you could just defer it but i think it gives an error after like 15 minutes
ah
@smoky sinew and if i want to make interaction response for embeds displayed only for the member who clicked ?
?
like that
ephemeral message
thx
Need some help with this. I’m looking to have my bot backup channels permissions to a json file and then if I do /restore it restores all of the permissions again
which part do you need help with
Backing up the permissions of the channel
yes and which part of that
im trying to show 1. how many people are in a vc 2.the max amount of people than can join the vc. 2 works perfectly fine but 1 is shown is the ss. also how would i show the space left in a vc? ping if u can help
value=f'{interaction.user.voice.channel.members}/{interaction.user.voice.channel.user_limit} '
What do you mean lmao, I’m tryna do /backup (backs up all channel permissions to a json file) then I can do /restore (restored all the permissions back)
use a list comprehension, for the second part you mentioned it's just basic subtraction?
have you written any code?
Not for this specific idea, I’ve done code for backing up messages, channels, roles, now I just need to do the channel permissions rn
so what do you think you'd need to do?
The issue I’m having is how can I even find what the channel permissions is, and backup it up to a json file
!d discord.abc.GuildChannel.overwrites
property overwrites```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
Changed in version 2.0: Overwrites can now be type-aware [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object "discord.Object") in case of cache lookup failure
you'd have to make this json-friendly somehow
so you can just get the ID of the first one
and then for the second one, get the Permissions objects from the permission overwrite, and then use permissions.value on it
so your json data would look something like ```py
{
"channels": {
channel_id: {
role_id: [allow, deny],
role_id: [allow, deny],
role_id: [allow, deny]
}
}
}
hey man, i don't mean to bother you but what vs code theme is that? i am guessing monokai winter night but not sure
may i ask why do you need those ifs when you do same thing for both cases ?
Because, as Down said, you added to ifs that will execute ALWAYS because in one of then you are checking if the interaction's user is not the guild owner, if so, it returns the embed; in the second if you are checking if the interaction's user is the guild owner, that will return the same embed.
Remove the if interaction.user != interaction.guild.owner, because if it is not the owner, it will happen always
Hello, why when I do /clear number:2, I don't get the "test" message. I get it when when I do /clear number:1. Either way, the messages are deleted.
import discord
from discord.ext import commands
from discord import app_commands
import json
class clear(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot=bot
@app_commands.command(name='clear', description="purge")
@commands.has_permissions(administrator=True)
async def clear_messages(self, interaction: discord.Interaction, nombre: int):
await interaction.channel.purge(limit=nombre)
await interaction.response.send_message("test")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(clear(bot),guilds = [discord.Object(id=guild_id)])
with open("./config.json", "r") as config_file:
config_data = json.load(config_file)
guild_id = config_data["guild_id"]
await register_cogs_async()
await client.add_cog(Commands(client))
TypeError: object NoneType can't be used in 'await' expression
i think the delete_messages endpoint is still fairly slow to respond, so you should defer before purging and then respond using the followup webhook
a full traceback is preferable, but what library and version are you using? await bot.add_cog(...) is only supported in discord.py 2.0+
Traceback (most recent call last):
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\chain\Desktop\Recover Cord\bot\bot\bot.py", line 42, in on_ready
await register_cogs_async()
File "C:\Users\chain\Desktop\Recover Cord\bot\bot\bot.py", line 37, in register_cogs_async
await client.add_cog(Commands(client))
TypeError: object NoneType can't be used in 'await' expression
Thanks, Upgrading my discord.py version fixed the issue
That's to say ? how to do ?
any way to create a hyperlink to text message app? inside of an embed
A what now?
I want to be able to open my imessage app directly from discord via link
if that makes sense
Don't think Discord has that capability.
How to update discord python version in replit
just open your repl and in tools there is packages you can install uninstall or update libraries from there
Can u give me ss?
is there a possible way change the display of this timestamp while it still being that format when you hover over it
Don't think so
u wanted to update discord so you should search that
Ya i was teaching from u how to update python version in replit
yeah just search discord.py there
Ok
if its latest version then u will see only remove button
Being what format
and i think repl automatically updates packages on startup
Let me see
Tell me the latest python version?
for python its 3.11 something and for discord.py it v2.2.3
Ok tq nice to meet u

I am getting this error, I am understanding how to fix it
Something went wrong while restoring permissions: Guild.create_text_channel() got an unexpected keyword argument 'type'
use the correct methods for each channel type
AllowedMentions
bot = commands.Bot(
..., # rest of your arguments go here
allowed_mentions=discord.AllowedMentions.none()
)
AllowedMentions.none is the safest bet, then when you need to ping anyone you would have to set the allowed mentions per message
Hey! I am having an issue with my cogs. I had everything in one file but decided to move it into multiple. I made it print when cog was loaded but if I execute a command it says the command is not found
import discord
from discord.ext import commands
import yaml
import os
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
# Load the configuration from config.yml
with open("config.yml", "r") as f:
config = yaml.safe_load(f)
# Load the cogs
async def load_cogs():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
try:
bot.load_extension(f"cogs.{cog_name}")
print(f"Loaded cog: {cog_name}")
except Exception as e:
print(f"Failed to load cog: {cog_name}\n{e}")
# Run the bot
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
await load_cogs()
bot.run(config["bot"]["token"])
2023-06-10 00:41:13 INFO discord.client logging in using static token
2023-06-10 00:41:14 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: a4cb05f66ae333d0b947ad19e57ce0e9).
We have logged in as HDR#0576
c:\Users\htxjc\Desktop\NEW BOT\bot.py:19: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f"cogs.{cog_name}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: check_command
Loaded cog: clear_command
Loaded cog: deposit_command
2023-06-10 00:41:21 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "deposit" is not found
.load_extension is awaitable
yeah for some reason the commands still dont work
i am not sure why. cogs are loaded
do you await .load_extension ?
yes I get even more errors
so show them
Extension 'cogs.help' raised an error: TypeError: object NoneType can't be used in 'await' expression
c:\Users\htxjc\Desktop\NEW BOT\cogs\leaderboard.py:36: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(LeaderboardCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog: leaderboard
Extension 'cogs.leaderboard' raised an error: TypeError: object NoneType can't be used in 'await' expression
c:\Users\htxjc\Desktop\NEW BOT\cogs\send.py:59: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(SendCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog: send
Extension 'cogs.send' raised an error: TypeError: object NoneType can't be used in 'await' expression
the setup function in a cog must be async
PS C:\Users\htxjc\Desktop\NEW BOT> & C:/Users/htxjc/AppData/Local/Microsoft/WindowsApps/python3.11.exe "c:/Users/htxjc/Desktop/NEW BOT/bot.py"
2023-06-10 01:49:11 INFO discord.client logging in using static token
2023-06-10 01:49:11 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 85a7588e1f8559f3af3240782e401909).
We have logged in as HDR#0576
Failed to load cog: add.remove
No module named 'cogs.add'
c:\Users\htxjc\Desktop\NEW BOT\cogs\bal.py:33: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(BalanceCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: bal
Failed to load cog: check.clear
No module named 'cogs.check'
c:\Users\htxjc\Desktop\NEW BOT\cogs\coinflip.py:117: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(CoinflipCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: coinflip
c:\Users\htxjc\Desktop\NEW BOT\cogs\deposit.py:99: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(DepositCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: deposit
Failed to load cog: help
Extension 'cogs.help' raised an error: SyntaxError: invalid syntax (help.py, line 27)
Failed to load cog: leaderboard
Extension 'cogs.leaderboard' raised an error: SyntaxError: invalid syntax (leaderboard.py, line 35)
c:\Users\htxjc\Desktop\NEW BOT\cogs\send.py:59: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(SendCog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Loaded cog: send
2023-06-10 01:51:02 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "send" is not found
The loaded cogs still dont work as commands
bot.add_cog must be awaited as well
2023-06-10 01:59:04 INFO discord.client logging in using static token
2023-06-10 01:59:05 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 703aaf5dbd20fecd90c1f9a5ac4d7e88).
We have logged in as HDR#0576
Failed to load cog: add.remove
No module named 'cogs.add'
Loaded cog: bal
Failed to load cog: check.clear
No module named 'cogs.check'
Loaded cog: coinflip
Loaded cog: deposit
Loaded cog: help
Loaded cog: leaderboard
Loaded cog: send
well its working now
thank you
👍
this cog wont load
import discord
from discord.ext import commands
import json
class EconomyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def check(self, ctx, user: discord.Member):
user_id = str(user.id)info["balance"]
if user_deposit is None:
gain = "This user has not deposited"
await ctx.send("This user has not made a deposit.")
# Add more economy-related commands here
async def setup(bot):
await bot.add_cog(EconomyCog(bot))
(cleared my code because msg was too long
yes
Dunno then, code is okay
Oh wait nope
Syntax error here:
user_id = str(user.id)info["balance"]```
The heck this is
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Paste full code there
Well from first view I don't see anything wrong either
Is there an error on load or it just doesn't load
could it be from the name? "Failed to load cog: add.remove
No module named 'cogs.add'
Loaded cog: bal
Failed to load cog: check.clear
No module named 'cogs.check'"
how does your file structure looks like in cogs folder
Anyway show your code which is responsible for loading extensions
async def load_cogs():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
try:
await bot.load_extension(f"cogs.{cog_name}")
print(f"Loaded cog: {cog_name}")
except Exception as e:
print(f"Failed to load cog: {cog_name}\n{e}")
ok it loaded now
the issue is you can have a . in the name
So the name was check.clear.py
I removed the . and it loaded
yeah you cant have dots
channel = bot.get_channel(channel_to_send_messages)
em = discord.Embed(color=0xFFD700)
em.add_field(name='Current Not Expired Keys', value=f'<@{user}> key isnt expired' + "\n" + "expire date: " + expire + "\n" + "Key: " + key)
await channel.send(embed=em) ```
the code above keep sending the non expired keys non stop how can i make it send each non expired key only once?
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.message_content = True
intents.reactions = True
intents.members = True
intents.bans = True
client = discord.Client(intents=intents)
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.channel.id == 1109981654438662144:
member = message.author.id
channel = client.get_channel(988420709372006403)
await channel.send(f"?ban {member}")```
dyno isnt executing the command for some reason
You cant execute bot commands via another bot
You can ban this member by yourself using member.ban
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
There is no error
But prefix not work
I will show you the code
`` import discord
from discord.ext import commands
import os
bot = discord.ext.commands.Bot("?", intents=discord.Intents.default())
@bot.command()
async def hi(ctx):
ctx.send("hello !!")
@bot.event
async def on_ready():
print("Online !!")
token = os.environ['Token']
bot.run(token)
``
Oh I miss await
.send is awaitable
I will try
Also why import commands and still use full Path for commands.Bot
Command 'verify-setup' raised an exception: ValueError: Circular reference detected```
what does this mean
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(interaction: discord.Interaction, channel: discord.TextChannel, *, message_to_verify: str, verified_role: discord.Role):
db[f"vchannelid {str(interaction.guild.id)}"] = channel.id
db[f"vmessage {str(interaction.guild.id)}"] = message_to_verify
db[f"vrole {str(interaction.guild.id)}"] = verified_role
channel = db[f"vchannelid {str(interaction.guild.id)}"]
channel1 = client.get_channel(channel)
channel1.send(f"type {message_to_verify} to verify")
await interaction.response.send_message("verification system setup")
channel2 = client.get_channel(1112053260879147130)
await channel2.send(f"verify-setup command used by {interaction.user}")``` my code\
extensions
😭
Guys any idea how to get started on discord chat bot like is there any free api for it?
you're looking for an open-source language model?
that you can run from your computer?
Yes
that's gonna require a good computer though
and i doubt you can find an API for free
Not necessarily
Depends what size you want it, some are small - hence less good - some are much bigger and obviously much better and resources eaters
a model with 7 billion parameters has the knowledge of a toddler and requires 16 gigabytes of memory to even run
Pretty shit then
falcon is actually one of the better ones
channelv = db[f"vchannelid {str(message.guild.id)}"]
channel2 = client.get_channel(channelv)
if message.content in channel2:
await message.delete()
``` this doesnt delete any messages in the channel
And it's in fact better than the average GPT-3 (according to stats)
if message.channel.id == channelv
The comparisons you're making are pretty weird
yeah ik
You're checking if the content of the message is in the channel object
You just want to check if the channel ID corresponds
channelv = db[f"vchannelid {str(message.guild.id)}"]
if message.channel.id == channelv:
if message.content:
await message.delete()``` is this how?
is llama.cpp the same model as llama?
Yes
both falcon-40b and falcon-40b-instruct still outperforms llama-65b and llama-40b in mmlu
Though does it by x4 since it uses x4 more resources
channelv = db[f"vchannelid {str(message.guild.id)}"]
if message.channel.id == channelv:
if message.content:
await message.delete()``` I tried this and doesnt work
Print them both and check their types as well, you may need to convert one
channelv = db[f"vchannelid {str(message.guild.id)}"]
if message.channel.id == channelv:
print("channel id tick")
if message.content:
print("message tick")
await message.delete()``` nothing prints
When I mean print them both and check their type I mean print message.channel.id and channelv before the if-statement and check their type
ohhh
how would i print? because i cant just print inside of the event with no if statement
....
channelv = db[f"vchannelid {str(message.guild.id)}"]
# here
print(message.channel.id)
print(channelv)
# here
if message.channel.id == channelv:
if message.content:
await message.delete()```
That's like... Even more than beginners knowledge...
thats what i did.. py channelv = db[f"vchannelid {str(message.guild.id)}"] print(channelv) print(message.channel.id) if message.channel.id == channelv: if message.content: await message.delete()
nothing printed
Then that location of the code doesn't even get executed
Your code never reaches that in the first place
oh.
what do i do
Investigate why it doesn't reach that
Check you don't have some returns, check your event (if it's an event) if correctly set up, etc.
Investigate a bit yourself, add some print statements around the code etc.
the things under it works
ok
above it there is an else
oh i found something
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 433, in on_message
await message.delete()
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/message.py", line 841, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/http.py", line 740, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
172.31.196.1 - - [10/Jun/2023 10:12:21] "HEAD / HTTP/1.1" 200 -``` i have a error
unkown message
discord_server = ["discord.gg"]
if message.author.guild_permissions.ban_members:
pass
else:
if any (word in message.content.lower() for word in discord_server):
key = db.keys()
db[str(message.guild.id)]
if f'{message.guild.id}' not in key:
pass
else:
await message.delete()
await message.channel.send(f"{message.author.mention} you can not send discord servers here", delete_after=20)``` this is above it
it is doing something to my message.content thing
how can i seperate it
Guys how can I make a ticket system using discord.py?
fixed thank you
make a database, create a new text channel and add it to the database
@smoky sinew You wanted to help me create an Ai chatbot
i did?

I am using msedge selenium to get screenshot of a website but due to cloudflare every screenshot is just cloudflare verifying website how to over come this issue
No, you just asked me if I want to use an opensource project or a paid project
ok
You don't, that's the point of CF - preventing bots
But can i fetch a img from the give url
You can, if they don't use CF
Thanks mate.
I mean using the posts channel
How does one stop an exception from propagating when a cog-level error handler handles it
I recall something about returning True/False stopping propagation but it neither worked nor is documented anywhere
talking about disnake
everything is possible
Hello, I made a command that deletes X messages from a room. When the bot deletes more than 1 message, The bot does not respond and I have an error...
import discord
from discord.ext import commands
from discord import app_commands
import json
class clear(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot=bot
@app_commands.command(name='clear', description="purge")
@commands.has_permissions(administrator=True)
async def clear_messages(self, interaction: discord.Interaction, nombre: int):
await interaction.channel.purge(limit=nombre)
await interaction.response.send_message(f"{nombre} messages supprimés")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(clear(bot),guilds = [discord.Object(id=guild_id)])
with open("./config.json", "r") as config_file:
config_data = json.load(config_file)
guild_id = config_data["guild_id"]
The error:
[2023-06-10 14:59:43] [ERROR ] discord.app_commands.tree: Ignoring exception in command 'clear'
Traceback (most recent call last):
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\steev\Desktop\discord bot\cogs\clear.py", line 14, in clear_messages
await interaction.response.send_message(f"{nombre} messages supprimés")
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 799, in send_message
await adapter.create_interaction_response(
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\steev\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Defer your command
This error is happening the bot fails to receive a response in the normal 3 sec so defering it will increase the time to 15min
how to Defer the command?
For defering add a line under your code under the async functionawait interaction.response.defer()
And change the await interaction.response.send_message('...')
toawait interaction.followup.send('...')
import discord
from discord.ext import commands
from discord import app_commands
import json
class clear(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot=bot
@app_commands.command(name='clear', description="purge")
@commands.has_permissions(administrator=True)
async def clear_messages(self, interaction: discord.Interaction, nombre: int):
await interaction.channel.purge(limit=nombre)
await interaction.followup.send(f"{nombre} messages supprimés")
await interaction.response.defer()
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(clear(bot),guilds = [discord.Object(id=guild_id)])
with open("./config.json", "r") as config_file:
config_data = json.load(config_file)
guild_id = config_data["guild_id"]
For future reference there can be only 1 response in your command as for the other responses you use followup
The defer line should be under async
You need to defer before doing something that takes a long time to complete
import discord
from discord.ext import commands
from discord import app_commands
import json
class clear(commands.Cog):
def __init__(self, bot:commands.Bot) -> None:
self.bot=bot
@app_commands.command(name='clear', description="purge")
@commands.has_permissions(administrator=True)
async def clear_messages(self, interaction: discord.Interaction, nombre: int):
await interaction.response.defer()
await interaction.channel.purge(limit=nombre)
await interaction.followup.send(f"{nombre} messages supprimés")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(clear(bot),guilds = [discord.Object(id=guild_id)])
with open("./config.json", "r") as config_file:
config_data = json.load(config_file)
guild_id = config_data["guild_id"]
Yup looks good
bot not responding "{nombre} messages supprimés"
Are the messages being deleted??
AttributeError: 'Member' object has no attribute 'server'
@bot.event
async def on_member_join(member) :
role = discord.utils.get(member.server.roles, id = "1115042589532487820")
await bot.add_roles(member, role)
await bot.send_message(member, "**Welcome to our server !**\n\n> Make sure to take your roles in [#1115049367829749894](/guild/267624335836053506/channel/1115049367829749894/) !\n> Don't forget to contact us if you need help (in tickets).")
!d discord.Member.guild
The guild that the member belongs to.
In discord it's guild
Where did you get this code from
i made it
yes but the bot
do not answer
Doubt it, it seems ancient
Can u get a ss
And bot.send_message doesn't exist
how can i send then ??
ss?
Screenshot
!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 "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 "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "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 "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 "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Read the docs
What output you are getting when u run the command
thx
delete only 1 message and do not return a message
Hello I am currently writing a dashboard for my discord bot and using the oauth 2 to get all of the text channels in the selected guild. I am currently getting the 403 missing access error when I am trying to get all of the channels.
{'message': 'Missing Access', 'code': 50001}
botheaders = {'Authorization': f'Bot {config.token}'}
channels_response = requests.get(f'{config.discord_api_base_url}/guilds/{guild["id"]}/channels', headers=botheaders)
This is what I am currently using, it gets the guild id and puts it in the url and discord uses the bots auth token to get the channels.
It's probably deleting the bot is thinking message
rawe le/a francais(e)
Try deferring it in ephemeral mode
For ephemeral await interaction.response.defer(ephemeral=True)
Issue fixed!
The guild["id"] was repoorting the first guild that it found that the user had manage_guild permission to not the guildid that it is trying to actual edit. I had fixed this by getting the guild_id from the select_guild template.
Thank you so much !
Btw u can add a delete_after=time in seconds
Line in followup if u want to auto delete the ephemeral message
Why when I put intents the prefix not work?
Show your code
Am i the only one lazy enough to even click that dismiss this message
Can you insert a timestamp markdown in a field value of an embed?
Yes
got this btw
`` import discord
from discord.ext import commands
import os
bot = discord.ext.commands.Bot("?", intents=discord.Intents.default())
@bot.command()
async def hi(ctx):
await ctx.send("hello !!")
@bot.event
async def on_ready():
print("Online !!")
token = os.environ['Token']
bot.run(token) ``
round(number, ndigits=None)```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.
For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.
For a general Python object `number`, `round` delegates to `number.__round__`.
it's not markdown it's custom syntax
commands.bot would be good
ight thx a lot
You need the message_content intent
Didn't understand
!d discord.Intents.message_content - enable this intent
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
Sorry I'm beginner in bots
the message content allows your bot to read messages which its not mentioned in
No message_content intent
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix:"?", intents=discord.Intents.default())
@bot.command()
async def hi(ctx):
await ctx.send("hello !!")
@bot.event
async def on_ready():
print("Online !!")
token = os.environ['Token']
bot.run(token)
this should be good
How I mention it
Like normal users
discor developer portal where you create your bot and fetch its token
@naive briar
don't mention it, enable the message content intent instead
I mention it there
Guys how can I get event for a post create in a form channel?
intents = discord.Intents.all()
and change your intent line to intents=intents
should be good
Why putting intents.member when u enabled all?
ahh yeah my bad 
When I don't mention it it goes error and tell me mention it
no it doesn't
I will try this
don't use Intents.all()
Yeah instead do
intents=discord.Intents.default()
intents.message_content=True
It makes big error
then show it
I can't copy
why you cant
Ok
(he's using replit)

The error already explained how to solve itself, didn't it
Enable privileged intents
It's too long
what is too long
It's enebled
._.
Then the error wouldn't be raised
im not guiding you to read whole stack trace just read error message at the bottom
Guys is there any event for post create in form channel?
screenshot
Ok
did you save it?
are you using token for this application?
bruh
Yes
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.

you need to check if channel is of type ForumChannel
post create in form channel
oh
well there must be something since python sends this nice embed in #1035199133436354600
!src
called it
just on_message event checking if its thread
Top tier chatbot
Lol
Are posts considered threads?
Forum channels are

