#discord-bots
1 messages · Page 297 of 1
Only reason I know about narcolespy is because of that series
The mysterious benedict society or smth
But I enjoy doing some coding projects so I make time during the evening on my weekends. My little escape from commercial plumbing lmfao
Hi, there's a free hosting website?
(where can i add the code i made and run on a public/private server)
Free hosting isn't good
Since you are using shared ips
So if it gets banned all the bots stop working
Can someone help please
I'm trying to get before.channel, but it gives out a NoneType, although everything is fine with after.channel. How to fix it?
library?
!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.
I know but the error is confusing
It isnt adding app_commands
I can't see the traceback, so I can't tell what's wrong 🤷
Update discord.py, reinstall if needed
Seems like u are using pycord
?
But you are trying to app_commands that exist in discord.py
Seems like the before channel is returning none try to print what it returns (like name)
Yea cause im beginner
Welp then use the modules for pycord
Not discord.py
I think in pycord it is slash_commmands
Tho not sure u should check the docs
before.channel is None
Depending on the event it makes sense so yeah 
hi everyone I want to create a python bot any useful resources to get started ???
https://fallendeity.github.io/discord.py-masterclass/
has some of the basics so far
A hands-on guide to Discord.py
#discord-bots message follow this for slash commands
@client.command()
async def userinfo(ctx, *, member: discord.Member = None):
if member is None:
member = ctx.author
embed = discord.Embed(title="User Info", color=discord.Color.blue())
embed.set_thumbnail(url=member.avatar)
embed.add_field(name="Username", value=member.name, inline=True)
embed.add_field(name="ID", value=member.id, inline=True)
embed.add_field(name="Status", value=member.status, inline=True)
embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d"), inline=True)
embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d"), inline=True)
embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)
# Send the user information as an embed
await ctx.send(embed=embed)
the status always shows as offline, any clue?
You have presence intent enabled?
.
i think so one sec
It's a privileged intent so check dev portal too
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead.
Try printing the status in your terminal
Tho it's pretty weird that it doesn't show idle
wait
i've figured it out i think, it isnt idle its me which is showing offline for some reason
why? idk
Welp if your status is invisible then it will show offline
yeah but it isnt
Welp try using get_user or fetch_user method to get the status
Tho I'm not sure what causing that issue
But you can try the above two methods
To do that
how can i run 2 tasks.loops at the same time without getting this error:
RuntimeError: Task is already launched and is not completed.```
Asyncio.gather()
oh
I have this error when i click a button in my message :
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'
here is the code :
class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
only the command is working well
Swap the position of the button and interaction parameter
In discord.py, interaction always come before the item in UI callbacks
Its working thanks !
I don't think that's possible due to how it's implemented
Oh gather won't do it?
No
What's the problem of just starting them like
task1.start()
task2.start()
That's the same as gathering
And the error is because he is trying to run the same task
I think they were asking how to run the same task twice 🤷
task1 = tasks.loop(...)(function)
task2 = tasks.loop(...)(function)
can work
very weird to run it twice though
Oh I thought he was trying to run 2 tasks concurrently
task2 = task1?
That will give "task is already launched" i am sure
hello I have a problem with my code when I do !start [id] the bot does not connect thank you for helping me
import discord
from discord.ext import commands
active_bots = {}
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def start(ctx, id):
# Vérifiez si le bot avec l'ID donné n'est pas déjà actif
if id not in active_bots:
bot_instance = start_bot(id)
if bot_instance:
active_bots[id] = bot_instance
await ctx.send(f"Bot {bot_instance.user.name} démarré avec succès!")
else:
await ctx.send("Impossible de démarrer le bot avec cet ID.")
else:
await ctx.send("Ce bot est déjà actif.")
@bot.command()
async def stop(ctx, id):
# Vérifiez si le bot avec l'ID donné est actif
if id in active_bots:
stop_bot(active_bots[id])
await ctx.send(f"Bot {active_bots[id].user.name} éteint avec succès!")
else:
await ctx.send("Ce bot n'est pas actif.")
def start_bot(id):
try:
with open("tokens.txt", "r") as file:
tokens = file.read().splitlines()
if id in tokens:
bot_instance = commands.Bot(command_prefix='!', intents=intents)
@bot_instance.event
async def on_ready():
print(f'Connecté en tant que {bot_instance.user.name}!')
bot_instance.run(id, bot=False)
return bot_instance
else:
return None
except Exception as e:
print(f"Erreur lors du démarrage du bot : {str(e)}")
return None
def stop_bot(bot):
if bot:
active_bots[bot.user.id].logout()
del active_bots[bot.user.id]
#
@bot.event
async def on_ready():
print(f'Connecté en tant que {bot.user.name}')
# Lancer le bot
with open("YOUR_BOT_TOKEN.txt", "r") as token_file:
bot.run(token_file.read().strip())
Does it show any errors
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
?
aa

You should also get a warning about it
Kinda sus if you ask me
the whole start_bot looks sus
Running multiple bots with the same code 
bot=False was a method to run selfbot back in the days wasnt it
yea
This is definitely old selfbot code that I don't think will work anymore lol
It wont but still selfbot is selfbot
I have this error when trying to repress my button :
AttributeError: 'Button' object attribute 'disabled' is read-only
class MyView3(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Click me to EXPRESS YOUR RAGE", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self , interaction , button):
Button.label = "No more pressing!" # change the button's label to something else
Button.disabled = True # set button.disabled to True to disable the button
await interaction.response.send_message("**I am going to implode.**") # Send a message when the button is clicked
Here is the code
Because you disabled the button
Did you mean button.disabled, not Button.disabled?
x) i changed it cuz it wasn't placed after async def so it was giving me error
so i was thinking i missed a caps
No it needs to be lowercase
You also need to edit the original message with self to implement those changes
PS C:\Users\kiera\Desktop\CDC Discord Bot> & C:/Users/kiera/AppData/Local/Programs/Python/Python311/python.exe "c:/Users/kiera/Desktop/CDC Discord Bot/main.py"
`import discord` import detected. Interactions.py is a completely separate library, and is not compatible with d.py models. Please see https://interactions-py.github.io/interactions.py/Guides/100%20Migration%20From%20D.py/ for how to fix your code.
Traceback (most recent call last):
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 5, in <module>
class MyBot(commands.Bot):
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 9, in MyBot
@commands.event
^^^^^^^^^^^^^^
AttributeError: module 'discord.ext.commands' has no attribute 'event'
PS C:\Users\kiera\Desktop\CDC Discord Bot>
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Ok where did u learn this
this is NOTHING like discord.py
Mixing discord.py with it's fork 
I am pretty rookie at Python but I like to be ambitious
What am I doing wrong/what is causing this error?
First of all discord.py and interactions shouldn't be used together. Choose one and use it
AttributeError: module 'discord.ext.commands' has no attribute 'event'
🫠
Okay, I think I need to use interactions then as I am using slash commands and options within them.
discord.py has slash commands :/
but you can use what you want
discord.py already support slash commands since version 2.0
I never knew that.
🤣
About error - since you are subclassing the bot, you don't need event at all. on_ready is method of Bot class, just override it
Okay, is it worth even using a class for the bot?
I am trying to get into the practice of always using them but I am getting the feeling that it won't prove useful for this case
It's ok, but don't put commands there.
It's strange to make commands methods of the bot
Don't put them inside of the class?
ye
Okay
What would I be putting in the class? Just the slash commands and then when defying the functions, I do it outside of the class?
Any extra functionality you'd add there or override. Like adding custom method to do bot.my_cool_method() or variable.
Or overriding methods like on_ready, on_message and so on
Is there a singular library I can use for my code? As in can I just use interactions or just use discord.py
Any of them. From these two i'd choose discord.py.
Okay, thank you.
How'd I add in the slash command using discord.py?
Is it the same as interactions?
nope
Would this work below: (It was made using ChatGPT4 so I have something with my use case to refrence from.)
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option
# Create a bot instance
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
slash = SlashCommand(bot, sync_commands=True)
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(
name="enlist",
description="Enlist in the CDC.",
options=[
create_option(
name="gamerscore",
description="What is your gamerscore?",
option_type=4, # INTEGER
required=True,
),
create_option(
name="name",
description="What is CDC name going to be? It must be one word and be professional.",
option_type=3, # STRING
required=True,
),
create_option(
name="division",
description="What division would you like to join or work towards?",
option_type=3, # STRING
required=True,
choices=[
create_option(
name="Infantry",
value="Infantry"
),
create_option(
name="Logistics",
value="Logistics"
),
create_option(
name="Military Police",
value="Military Police"
)
]
)
]
)
async def enlist(
self,
ctx: SlashContext,
gamerscore: int,
name: str,
division: str
):
member = ctx.author
try:
await member.edit(nick=f"E-1 | CDC {name}")
if division == "Infantry":
# Add role logic here
pass
elif division == "Logistics":
m = "Logistics is currently unavailable. You have been assigned to Infantry."
await ctx.send(m)
elif division == "Military Police":
# Add role logic here
pass
else:
m = "Invalid division. Please choose from Infantry, Logistics, or Military Police."
await ctx.send(m)
except Exception as e:
m = f"An error occurred: {str(e)}"
await ctx.send(m)
finally:
m = "Welcome to the CDC! Make sure to introduce yourself, get familiar with the rules, and engrave yourself with the procedures."
await ctx.send(m)
# Add the cog to the bot
bot.add_cog(MyCog(bot))
# Run the bot
bot.run('YOUR_BOT_TOKEN')
Try it and see
how do you set an embed's thumbnail to be the avatar of a user
!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.
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset) for the avatar the user has.
If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
could also be Choices, hard to tell from that
I will try both ty for telling me
sure, just know that autocomplete is dynamic, choices is static, so depends on your usecase
What is the best module to make a discord bot in python which supports slash commands? And also pls link me any resources for that module so I can start working with it.
Also, I have a discord bot working with discord.py module. But it doesn't supprt slash commands because it was made 3 years ago. Is there any easy to make it use slash commands?
discord.py supports slash commands but you can use disnake ( which is a discord.py fork ) for an easier interface
if you want completely new environment then hikari with hikari lightbulb is a nice choice as well
I made a bot having Instagram features but it's not growing 😔
Will disnake be easier to convert my existing bot to work with slash commands?
It's all about your preference
Choose whatever u feel comfortable with
discord.py has a hybrid_command system that integrates slash commands behind the scenes, so you could use that if you already have a working bot
That's make them both a prefix and slash
So it's depending on the use case
What if he wants only slash commands?
Figured I would give another option, and tbh it's relatively easy to stop prefix with minimal effort
It's not 100% guaranteed that it would stop it
Sometimes commands even work without processing in on_message event
I believe discord.py has process commands only in on_message
Yeah but sometimes it doesn't need to be used
What else processes them then?
I haven't used webhooks yet but I'd like to. Is the typical use to create a webhook every time you want to send a message with it? Or check if there's one for that channel before creating one? Or what
I don't know what you mean, the bot.process_commands is called in bot.on_message, so using bot.event for on_message will effectively remove it
The latter
It should be a webhook that the bot can use before creating
I'm just saying sometimes it isn't even needed and commands are working
Tho idk the reason for this happening
it is required for it to work, that's literally where command processing came from
disnake works with old discord.py ( when 2.0 was in development) codebase for most of the part
I feel like you're confused between listeners and events
Nope not confused I'm pretty sure about it
So check for webhook, if there's not one for this channel create one and use it, else edit the existing and send message?
You'd need provide a working code to prove that
Prefix commands won't work without it
Yes, tho, why edit the webhook? For what
Editing the webhook to match a user name and avatar. So multiple users can use the same webhook
Perhaps random bot.process_commands somewhere you had?
webhook.send have them, no need to edit the webhook itself
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
welcome
how to check how many people joined a server in a certain delay
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
Store the joined members in the way you want in that event
!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).
^^^
ty
Is there any working code for a music bot with slash commands using disnake?
probably not why not code it yourself
actually I have one which was working fine with discord.py, I have trouble changing it to disnake 
Olá
Why change it to disnake if it was working on discord.py
changing it to slash commands
cause disnake is better, facts
Tbh i don't see the reason to change your entire to disnake
yeah that's true
mh but some things are implemented better
Anybody familiar with regex?
@bot.event
async def on_message(message):
msg = message.content.split()
lgth = len(msg)
rand = random.sample(msg, lgth)
rand = str(rand)
content = str(rand).replace("[","").replace("]","")
content = re.sub(r"(?s:'(.*)')\Z", r'\1', content)```
Trying to jumble someone's message and send it, but I need to remove the apostrophe before and after every word but not the ones inside the word. This works if a single word is sent but if there's multiples, it only removes the first and last one and idk how to get where I'm trying to go at this point
Show example text and result
Well if I use an apostrophe in a word such as that's then it goes in as "that\'s" so could I strip() something that doesn't exist if that's not the case?
Because that's why I was using regex, it mixes ' and " based on the input
strip will do nothing if it doesn't find the character you gave it
And will it strip the ones in the middle of the words
no
Pls help guys the pycord server doesnt help me
Lemme see your help post on the Pycord server lol
I asked 2 questions and waited alot no response
Dude they are volunteers like me. Give them time
So you use py-cord?
Can you run this script and show what it returns? print(__import__("discord").__copyright__)
pycord should have an abc module so it looks like a broken install; perhaps you installed both discord.py and py-cord and then uninstalled discord.py?
that did reproduce the error for me actually ```py
pip install discord.py py-cord
pip uninstall discord.py
py -c "from discord.commands import option"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "\site-packages\discord\commands_init_.py", line 26, in <module>
from .context import *
File "\site-packages\discord\commands\context.py", line 29, in <module>
import discord.abc
ModuleNotFoundError: No module named 'discord.abc'```
so er, uninstall any other discord package you might have then reinstall py-cord
your bot token is probably not the name of an environment variable
Sorry meaning?
have you set an enviroment variable with your token in it?
Ohh you mean a secret ?
yeah whatever replit calls it
I forgot to 😂
Thanks for reminding me lmaoo
regenerate your token now @slate swan
I did it already lol
I did it before I send this
Do I replace ‘BOT_TOKEN’ with the token or
Do I remove the [ aswell
no, you create an enviroment variabled named "BOT_TOKEN" and set it's value to the token
I did v
the point of it is to not include your token in the code
I mean for this command
Ohh really ?
yeah
So in the value I put token?
you put your token, yes
Now I got this error
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.
I don’t get the last step
Where it says you need to set the intents…
you should be able to just use the intents object it creates there as an example, there are a few other intents that are disabled by default that you can enable if you need them
I mean the code
intents basically tell discord what events to send to your bot
I already enabled the intents
yes, but you need to enable them in your code like shown in that embed
just copy code from here
embed code formatting is a little wack it looks like so
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)
I’m sorry I’m just new to this,
I have no clue ?
This is the code itself
just create you intents variable somewhere before the bot variable is created
from discord import Intents
intents = Intents.default()
intents.message_content = True
then pass that variable into the definiton for your bot (line 16)
bot = commands.Bot(command_prefix="!", intents=intents)
Can you speak in a way a dumba** would understand 💀
ooga booga copy paste first code before line 16 then on whatever line that is now put , intents=intents inside the parenthesis like shown in the second codeblock
Perhaps like this?
halfway there
put , intents=intents into parens on line 19
Nope, i stole the source from a. Guy 
who writes comments like that
No idea, ain’t my source
I think it’s a free source
It just guides you
So do I replace it ? Or add it
add
the guy got it from chat gpt 
Can you answer this question for me?
Would it be like this?
ngl that's like the first thing I did with programming
except it was javascript 💀
you have some shitty code at line 49
show your code
I fixed it but I also got this
Lmaoo
@slate swan
Why is that ? And how would I fix it
dont copy code from random sources, learn docs and make it yourself
Well okay, but how would I fix the error ?
i would rewrite this code completely
Pretty clear
You’re missing the arg intents
!d discord.ext.commands.Bot
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.
Yea one thing, (I’m a dumbass and this is absolutely not my code)
So I have no idea what to do here
discord.py isn’t recommended to beginners
I see
But you just mind helping me for this bit? Since it looks like your an experienced programmer?
I’ve already given you the solution
Basic OOP
Where would I put this command ?
Nowhere, it’s not a command
You also already have an instance of commands.Bot
You just need to pass the intents arg
This is extremely simple
Sorry can you just put it for me ? I’m really clueless and it’s 2 am trying to figure this out
I don’t spoon feed
Okay then 😂
Traceback (most recent call last):
File "main.py", line 45, in <module>
bot.loop.create_task(send_custom_message())
File "/home/runner/SleepyMoralDeveloper/venv/lib/python3.10/site-packages/discord/client.py", line 140, in getattr
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
Yep my solution will work
Since I’m doing discord.py
@bot.loop(seconds=1)
async def loop_1():
await send_custom_message()
@bot.event
async def on_ready(ctx):
loop_1.start()
...
This would be it?
How would I use the achryonisis main function and pass it?
@bot.loop(seconds=530)
async def send_custom_message():
...
# same code, but change
while not bot.is_closed():
# to
if not bot.is_close():
# and remove
await asyncio.sleep(530)
# add this thing on line 43
@bot.event
async def on_ready(ctx):
send_loop = send_custom_text.start()
# and remove thing that is on line 45
Like this?
Got this error lol
Remove line 47
Add colon (:) to the end of line 39
Add @bot.loop(seconds=530) after line 34
Sorry
Replace
@bot.loop(seconds=530)
With
@tasks.loop(seconds=530)
And add to start of the file
from discord.ext import tasks
Doesn't matter, where your imports are
first letter in "from" small
So I change from discord.txt to that?
Is that what you mean?
You have it already, just add ", tasks" to line 4
So close ahh you’ve been really helpful and patient thank you so much
And i see that you already have on_ready() function
Uh shuhh forgot, you don't need ctx in brackets....
So I would do?
So just add
send_custom_text.start()
To your on_ready function,
And remove that i asked to add
Which line?
Hold on I’m confused ?
Doesn't matter, just inside of it
After it will be okay
So hold on ? I add this where ? send_custom_text.start()
I’m a bit confused lol
To your on_ready() function
Like code that will be executed
@bot.event
async def on_ready():
send_custom_message.start()
print(f'We have logged in as {bot.user}')
And it's message, not text... Oh i am sleepy..
so send_custom_message.start()
Yes
And right indentation.. (spaces)
And removed extra space before that?
You still have extra space on start of line 24
24 and 25 should start on same column..
So same line?
Same number of spaces before ... Oh just figure it out by yourself.
There are few stupid mistakes, code should work if you fix them
And if you want to know what all that was
And if you understand python atleast on basic level
And became friends with OOP style
Im going to sleep, bye
Good night ! Thanks for the help
Remove lines
46, 45, 44
@slate swan
Done
Ok it for some reason doesn't know who is server
What do you mean?
I suppose
Weird
Check if that id is right
And if bot accaunt is in that server
I still didn’t invite the bot into server
So that is the reason
Change to is_closed then idk....
Sorry, what?
||I should get money for that kind of help||
Anyway, 2:23am, i am going to sleep, if you need help find someone else
Woops
Fine you’ll receive payment if you help me through out all of this
Or maybe even fix it yourself 
I will denie
20$?
Anything.
I don't think this place is supposed to be paid
I will just leave
Neither do I lol
You can learn python basics, and start to slightly understand what are you trying to do by yourself, or with help, here should be ton of people who want to help you to learn
But keyword is learn
I would after this project, but I need it desperately for something
With all steps, like checking documentations, experiments, and etc.
Oh I just change it to “if not bot.is_close”
Is that it?
Is_close does not exist
Try and see
Delete lines 40 and 41, take 4 spaces out of line 42.
It probably easier to make whole script for him.
I've been in and out of here all day, you're a Saint for sticking it out as long as you did
Any who can teach me how can i make invite tracker bot?
They absolutely is
Take 4 spaces out of line 41. Make the first letter line up with the c in channel above it
Hence the unexpected indent
no anime challenge creates a lot of time to spend
Make it look like this, but move line 41 to the left a bit
Oh sh*t did I delete it ?
Did I delete it?
Did you?
I think so 💀
Welp, time to scrap it 
Again, line 41.... 4 spaces.... to the left
Alright I got a child to put to sleep. Good luck!
okay guys
a friend recomended replit
anyone here knows how to use replit vps?
that is 24/07?
I recommend anything but replit
I advise against sharing a bot token in a public forum
I changed it Already
Before I even sent it
But with a new error I managed to add it back
.
I don’t see 4 spaces ?
Await needs to match indentation level of the 'channel' above it
Do you know what I mean when I say indentation level
Spaces ?
If you draw a line vertical down from where it says channel. The first letters should be on the same vertical line
You know, you've been here 3 hours now and I bet if you had read a python book or study guide for an hour you'd have this fixed an hour ago
import os
from discord.ext import tasks, commands
from discord import Intents
bot_token = os.environ['BOT_TOKEN']
class data:
server_id = 1147111605650325617
server = None
channel_id = 1147944228522053713
channel = None
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
send_custom_message.start()
print(f'We have logged in as {bot.user}')
@bot.command()
async def instagram(ctx, command: str, followers: int, url: str):
response = f"Command:
{command}\nFollowers: {followers}\nURL: {url}"
await ctx.send(response)
@tasks.loop(seconds=530)
async def send_custom_message():
await data.channel.send('/instagram followers 250 https://instagram.com/negregro1')
@send_custom_message.before_loop
async def before_send_custom_message():
await bot.wait_until_ready()
data.server = bot.get_guild(data.server_id)
data.channel = data.server.get_channel(data.channel_id)
if __name__=="__main__":
bot.run(bot_token)
@mighty pilot check this
You wrote the whole thing ??
Yea it's not hard to write. This code is not complex at all
Just for me bro
I honestly don’t deserve you bro 💀
why you won't recomend replit?
So that’s it?
Not counting that i made it on phone not existing from discord
I've heard nothing but bad things from people trying to use it
Wait so im done ?
thought it's one of the fewest that is 24/07
maybe we don't know how do use it
since a friend could use it
That ship should work, but i saw you made some additions
and plus this could be a temporary server for me since i can't pay for one
It's possible to use, sure
So do I delete the other code
And paste this one in?
Ask @mighty pilot
I guess yes?
I could misspell or mistake
Lmao idk best way to see is to hit run
I'm just a hobbyist with ideas I like to see happen
No such file: main.py
repl process died unexpectedly: exit status 2
Giving up. You can try again by clicking Run. You may need to fix the [interpreter] definition in the .replit file first.
i don't know how i fix this
Welcome to replit
From which directory are you running it?
Same as main.py?
I ran it
yea i misspeled
this one:
What was the misspell?
Idk
Mistake is probably on line 27 as Traceback says
And i probably added new line after colon

@hallow kernel
Congrats you can copy and paste. Sometimes.
(Sometimes) 
Sorry I can't help
What was the command btw?
need more information?
please Curome don't try to research that staff that you never saw, just because you feel so eager to knowledge. Just go sleep!!!
For the automation
also Curome, how do i contact the comunity of replit?
@hallow kernel good night
I feel that I'm the same way. Go get some sleep lol
Are 3 and a half hour that left even matter?
Better than no hours
I can’t seem to figure out the command 
Use /instagram
Doesn’t work lol
How do I make it pop up?
Isn’t it better?
Learn some stuff then come back
thats against instagram TOS & discord if i remember correctly.
Yea ik, it's a whole different layout
Oh really ? Cry bout it
It's a message that you manually edit
Doesn't actually interface with insta
botting statistics is against TOS 🤷♂️
It doesn’t acc bot
Sure
I'm not super familiar with the mumbo jumbo of all that, but it has no interactions with anything It's just a message that you manually edit
Is your bot in that channel
Yea
learn some stuff
if it doesnt bot then what does the command do then
What's the problem?
trying to integrate slash commands into a bot that violates TOS
How does it violate TOS
its a follow bot
huh
you run a command with how many followers you want a page to receive
or thats how its supposed to work
That's absolutely not what that code does lmao
what it looks like to me
ive read zero code and all i see is "follow bot" with a guy passing in an ig handle and follower amount
Then maybe look at some code? It takes his input and puts it into a message and sends that message every 530 seconds
wtf is the point of that
sends a message every once in a while. Believe me, he's not writing anything fancy like a follow bot he was in here for 3 hours troubleshooting that basic code that someone else wrote
i feel someone is slightly altering their code so we dont see its full functionality
Idk anything about it
This is the code he ended up running
remove your send custom message task. you don't need it
any bot that just sends messages on a loop is spam
data should be capitalized, library imports should be seperated from module imports
You shouldn't be running things in on_ready as well
Discrord py credi be like
Spam violates ToS?
it's just annoying. probably also violates tos as well
Why?
Ok imports separated is just some crazy unlogical reason.
But why data should be capitalized? I use it like variable. So it is variable.
Where then?
Subclass, run in setup_hook
pep8, also a class is very far from a variable
Outside of it so i could not use bot.run()? And use bot.login(), bot.start() in asyncio.run(main) ?
What's the difference in that case?
on_ready can be called multiple times during setup, there's also no guarantee it'll be run after the bot connects
Discord also has a chance to disconnect you for making API calls during setup
tldr don't do shit in on_ready
i have this script https://paste.pythondiscord.com/UR3Q wrong token btw and it sends this error who can help? I need some hours so if there is any questions feel free to hop on my dms and ask and ill answer later
What is the name of the environment variable containing the token?
That's module
Then you should do os.environ.get("os")
Mm yes you try to access token by token
That kills the point lol
Indeed
You access token by name of environment variable, not by token itself
Ty, ill check next time
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
Ik but they dont appear
Show how you are using it
It's not wrong, just a different thing
Choices are static, autocomplete are dynamic and they update each time you type something
Show where you passed it. Here is only the definition of the function
But yeah, you have just a static list so choices would be better
https://guide.pycord.dev/interactions/application-commands/slash-commands#autocomplete example of both
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
How do i use choices
Ty
in a ticket bot, is sending messages in a forum or normal channels better? and if so why
personally, i'd just have a channel which has the embed and button to create a ticket, and upon clicking the button, it pops up a modal which allows the user to specify why they're opening the ticket & more information etc
?
but, why do some people say that sending messages with a bot in forum channels are better than normal channels?
🤷♂️ its all personal preference, theres no real benefit in doing each way, personally how i look at it
oh okay
Probably just because forum channels don't clog up your channel list
does anyone have any docs on how to create threads with a bot?
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.
New in version 2.0.
i did
avatar = user.avatar
embed.set_thumbnail(avatar)
it said that embed.set_thumbnail takes one positional arg but two were given, why?
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | f(123)
004 | TypeError: f() takes 0 positional arguments but 1 was given
!e
def f(*, x): ...
f(x=123)
@buoyant quail :warning: Your 3.11 eval job has completed with return code 0.
[No output]
Pass them as argument_name=value
so like
embed.set_thumbnail(*,avatar)?
No
Yes
(But avatar should be the link and not the Asset object as you have it now)
Look in the methods of the Asset
yes
so when i fix it it will work?
wait
idk how to fix it
When you fix something it works (unless you fix it in a wrong way)
What's your python experience
the first bot in my history
If it's your first python project I recommend finding a spoonfeeder getting more python knowledge first
Ofc it's easy
Just give code and spend lots of time figuring out issue of the beginner
sinceu seem a good scripter tell me what to do to make it run now
That sounds like a demand
what does demand mean

They told you hours ago
welp he didn't right anything in an alien language that's the most basic thing he's telling
you should at least know what's a variable
ok
If you're not willing to learn some basic knowledge it's going to be difficult to find someone to help you
Yea if you don't know the simple terms how are you going to know what they're telling you to fix lol
Yup
After running a discord server for a while I've learned nobody knows how to read anyways
Keep getting a warning message that message content is missing, I know it is enabled in my developer portal.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You did not enable it in the code
!d discord.Intents.message_content
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...
how do i set permissions/overwrites in a thread?
yes
hellos sirs and female sirs
how i can execute a command when someone mentions the bot but there is also cooldown on the command and it should also work perfectly fine
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix) attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
The cooldown stays the same from prefix commands
how it will know the comand to be executed
same as with just prefix
@mybot hello
will execute hello
@bot.command()
@commands.cooldown(1, 7200, commands.BucketType.user)
async def active(ctx):
roles=ctx.author.roles
print(roles)
perms = discord.AllowedMentions(roles=True)
role = discord.utils.get(ctx.guild.roles, id=1097188358322671616)
for i in roles:
print(i.id)
if i.id==role.id:
await ctx.send(role.mention, allowed_mentions=perms)
@bot.event
async def on_message(message):
if message.author==bot.user:
return
if bot.user in message.mentions:
bot.invoke(active)
how i can invoke the active command wit its cooldown working
Wdym in above scenario the cool down is by user
Invoke takes context, not command
Get message context and set ctx.command attribute to active, then use invoke with it. maybe this will be enough. I am not sure tho
Can i make ability to bot to update/add/remove its commands without restarting it?
Bot has add_command and remove_command methods
If you want to change code in them, loading code from the same file in already running script would be not really easy (if you don't have some cool code structure so you will need just to reimport these functions for example), you can use extensions and reload only one extension
The best way to do this is with extensions
Guys can someone provide a doc for a command that if you say !hello
It will send 2 messages that have a pause in between and the second message replies to the 1st
Nvm guys i found it
``@tree.command(name = "poll", description = "make a poll!", guild=discord.Object(id=1136519406508326962))
@app_commands.describe(topic = "write the topic")
@app_commands.describe(o1 = "write no 1 poll")
@app_commands.describe(o2 = "write no 2 poll")
@app_commands.describe(o3 = "write no 3 poll")
@app_commands.describe(o4 = "write no 4 poll")
async def poll(interaction: discord.Interaction, topic: str, o1: str, o2: str, o3: str, o4: str,):
user = interaction.user
emojis2 = ["1️⃣", "2️⃣"]
emojis3 = ["1️⃣", "2️⃣", "3️⃣"]
emojis4 = ["1️⃣", "2️⃣", "3️⃣", "4️⃣"]
embed = discord.Embed(title=None, description=None)
if o3.lower() == "n/a":
embed = discord.Embed(title=topic, description=f"""
- {o1}
- {o2}""", color=discord.Color.purple())
if o4.lower() == "n/a":
embed = discord.Embed(title=topic, description=f""" - {o1}
- {o2}
- {o3}""", color=discord.Color.purple())
if o3.lower() == "n/a" and o4.lower() == "n/a":
embed = discord.Embed(title=topic, description=f""" - {o1}
- {o2}""", color=discord.Color.purple())
embed = discord.Embed(title=topic, description=f""" - {o1}
- {o2}
- {o3}
- {o4}""", color=discord.Color.purple())
embed.set_footer(text=f"Action by {user.name} ({user.id})")
em = await interaction.response.send_message(embed=embed)
if o1 and o2 is not None:
for emoji in emojis2:
await interaction.user.add_reaction(emoji)``
the last line shows an error
pls help
are we supposed to guess what error it shows?
Traceback (most recent call last):
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 63, in poll
await interaction.user.add_reaction(emoji)
AttributeError: 'Member' object has no attribute 'add_reaction'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/FunnyElectronicDevelopment/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'poll' raised an exception: AttributeError: 'Member' object has no attribute 'add_reaction'
forgot about it sry
so .add_reaction is method for Message
you are doing it on Member object
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
oh tysm bro
but it still doesnt fix the error tho
what did you change?
Nothing will, if you still try to add a reaction to a user for some reason
for emoji in emojis2:
await add_reaction(emojis2, em)
it takes only one emoji ^
oh okay
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
You can simply use the REST API for that
This is the best free way
Error is pretty self explanetory
but how should i reply if reply isnt in it
btw its replying to a message
not a trigger
A followup is normally best for interactions
Idk how to do that
Do you have a doc or example for it
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Here's the docs for it, I've never used pycord so I'm not too sure if it's the same as dpy
What message are you trying to reply to tho?
If it's completely separate from the interaction you will need to get the message object, either by fetching it, or you could also get the partial message if it's cached.
So the bot sends a normal message and than asyncio.sleep(5)'s and than reply to the first message he sent
https://discord.com/api/v9/channels/{channel_id}/messages
payload = content : "message"```
Is the first message a interaction response or just a normal message?
ctx.send
So prefix command?
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.
It looks like a prefix command, is it not?
Idk got it from chatgpt cause my code is complex
Its prefix but supposed to be
slash cmd
This looks like discord.py as well
I suggest you don't use ChatGPT, it's outdated and you won't learn anything from it
Ok but can u help me with it
I just want to fix the error with the reply
Yeah, I don't understand how ctx is a interaction object tho
Are you sure this is pycord?
Yea its just async def dumbo(
ctx: discord.ApplicationContext
):
It was a joke lol, I thought it would be somewhat obvious
The code looks like discord.py code, so I suggest you switch to dpy
Ty i hate pycord fucking confusing as shit
Run this to get a clean install of discord.py
import os
import sys
py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands"
os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
bruh.
What IDE is this?
Its package tab of replit
Oh, don't use replit to run or host your bot. It's not made for what you're trying to do, and it can cause issues that are purely based off replit.
Use a real IDE like vs code
Im mobile only sadly 
Ikr im ruining my code on mobile kinda
it should work with dpy, you will just need to enable the message content intent
Anyone can help me with text recognition from image
How
You said "it's supposed to be a slash command" earlier, and this is not how you make slash commands with dpy. Read this gist if you would like examples and info on slash commands with dpy. Additionally, I recommend you change your prefix from / as it's bad UX.
intents.message_content = True
hi after trying this out of boredom, im getting an error and im confused rn
import requests
channel_id = input("Channel ID: ")
r = f"https://discord.com/api/v9/channels/{channel_id}/messages"
headers = {"authorization" : "pretend this is token"}
while True:
message = input("Message: ")
res = requests.post(url=r, headers=headers, data={"content" : message})
if res.status_code == 200:
print("successfully sent")
else:
print(res.content)```
bot has permissions and access to the channel
If you're using Intents.default() disabling presences is redundant because default doesn't enable any privileged intents
Not talking to you
oh
Requests is blocking
It's raw api + input so it doesn't really matters
This code is ok.. Maybe you forgot to add "Bot" in authorization?
There's no event loop running in this
Guys is there any example of a slash command and the slash command replies with a normal message? Ctx kinda doesnt work for me 😦
headers = {"authorization" : "Bot pretend this is token"}
``` you need to add `Bot ` before the token in authorization header
i dont remember if it's case sensitive or not but going with convention the first char needs to be uppercase
it's not case sensitive actually
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
webhook for normal messages
as i remember works only after replying, but maybe not
or just take the channel
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
How do i use it
Can you tell me please or send a example
It has send method
async def some_command(interaction):
await interaction.response.send_message("response")
await interaction.followup.send("normal message")
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix="-", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')
# KEEP THIS
bot.remove_command("help")
# KEEP THIS
@bot.command()
async def say(ctx, *text):
await ctx.send(' '.join(text)) # Join the text with spaces
bot.run("token")
someone tell me why my bot does nothing when i run the say command 😭
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
Prefix commands can't run without message content intent
you should also get a warning about it when you run it
first line of output
: )
@buoyant quail you are a lifesaver
You deserve to get a role here ngl none helped me better than you
this was helpful
and authorization didnt need to be capitalised
so any api request that i can see using the network tab, i can recreate by adding Bot to the auth header?
there are some endpoints that can be used only using Bearer tokens, but yes you can use most endpoints like this
https://discord.dev has all the endpoints exposed to bots
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
what version of dpy do you have?
One from before the name changes
that doesn't help. semver version?
lemme get it
2.3.1
i run 2.3.2 without any issues so idk what could the cause be
I'll upgrade now anyway
ok
figured it out
had nothing to do with the discord.py
friend decided to move his API endpoints without letting me know -.-
hello guys, i've been wanting to create a larger bot for a while now
but my only question is: what's the best way to sync a bot with a database?
i want to use mysql
my questions are stuff like: do i need just oen curosr active at all time? do i have a loop that makes sure the cursor is alive, do i need a queue for writing/reading data from the database?
Manual
And do not use MySQL. Use PostgreSQL
Connection pools are your answer
TL;DR: MySQL is a bad database. Don't use it unless you have literally no other option.
Why shouldn't I use MySQL?
- MySQL has no transactional DDL. This means that if you fuck up creating a table in the middle of a migration, you cannot rollback easily.
- MySQL has a lot of security issues. New zero-day vulnerabilities are found regularly.
- MySQL is owned by Oracle.
- MySQL is slow. It beats Postgres etc at some things, but once you move beyond basic queries it begins to slog.
- MySQL disconnects you randomly. Unless you setup your connection specially, it will break regularly.
- MySQL allows all kinds of insane data to be inserted. '0000-00-00' is valid in MySQL.
- MySQL is not ANSI compliant. You have to turn it on; even then it isn't fully compliant.
- MySQL has no feature advantage over other databases; PostgreSQL has many more useful features (such as RETURNs).
There is no reason to use MySQL over PostgreSQL, or even sqlite3. See also:
https://blog.ionelmc.ro/2014/12/28/terrible-choices-mysql/
https://grimoire.ca/mysql/choose-something-else
The terrible pitfalls I've gotten myself into while using MySQL — I've used MySQL for a while now, and there were lots of surprising things I needed to cater for. This is from a Django and MySQL 5.5 perspective...
oh isee
connection pool is like available connections i can use, and when no connection is available i just wait for a new one to be available right?
Connection pools are pools of connection that your bot can get, do stuff, and then release back into the pool. It's a far more efficient way to maintain connections instead of constantly spam creating new ones
If you are looking for saving data then have a look at postgres.
PostgreSQL(https://www.postgresql.org/) is one of the best relational databases which is most programmers' first preference. We call it Postgres because why not?
The python driver, asyncpg(https://magicstack.github.io/asyncpg/current/), provides asynchronous support for Postgres!
If you have prior experience with SQL then you can easily switch to Postgres. If you don't then you can take this interactive tutorial at https://sqlbolt.com
Have a look at this Example Code as well to get a quick start: https://gist.github.com/jegfish/cfc7b22e72426f5ced6f87caa6920fd6
its first time i see someone saying mysql is bad database
Yep it is. People have reported random disconnects with mysql
random disconnects cause of mysql or cause of the python library
MySQL
asyncpg does that to
i was getting a lot of connection is closed for no reason
I've used asyncpg in production and never had that happen
I would think it's the way you are maintaining the connections that is the issue
I've used PostgreSQL for 2 years and never had that happen to me
yes postgres is better than mysql but i wouldnt say that you shouldnt use mysql casue of that
i have a question, since I have a connection pool, is there any reason i should use asyncpg over psycopg?
Async
isn't a connection pool basically making psycopg asynchronous?
psychopg is synchronous i belive
Plus 3.89x faster compared to psycopg3
psycopg3 is but asyncpg is like 2-3x faster iirc
Asyncpg is also apparently 8.2x faster than node-pg
Based off of geometric means
Isn't mariadb basically the same as mysql? I've been using that for over a year with no issues, just make sure you set the connection timeout to a value reasonable for your application
Both are different
Mariadb was forked bc MySQL basically got owned by Oracle
Ah I see
Mariadb strives to maintain compatibility with mysql but I haven't seen a good maintained mariadb driver out there that can compare to asyncpg
I use the one in their documents. Pretty straightforward. It was recommended to me by a friend that gets paid to do IT and I'm just a hobbyist so anything used in commercial applications is probably good enough for me
Ah ok
I just always thought it was a more updated mysql, because that's how it was described to me
it is actually
How would I enable them in my code?
Would anyone here be able to share how they modeled their database for their discord bot, I have a few ideas but not sure which is the right approach
Depends on what you're doing. I have a level bot that stores info in a table which the keys are server ID and user ID then I just have their points. Seperate table for specific server info like roles assigned at specific levels and level up difficulty and a bunch of other parameters associated with it
do you have a table dedicated to each guild, for example the guild id being the primary key and then you make columns for all the info needed for that guild or do you just use the guild id as a key for entries in other tables?
My original layout had the guild ID as the table names, but then I wanted to change some functionality so I made it all one table for user points info and a seperate table for server specific info with the guild ID as key and a new column for each piece of info stored for that guild
So 2 tables, one for points which stores guild ID (key) user ID (key) and points and a seperate table with guild ID (key) and a bunch of parameters associated with it
https://github.com/No767/Kumiko/tree/dev/Migrations you can always take a look at my messy migrations for maybe an idea
For my design, each guild is unique. In fact, the id, which is the primary key, is the guild id
this is how i modelled the schema for my fairly simple starboard bot (ignore the crows feet, some of the relationships are more practically 0-1/1-1 because of triggers)
https://github.com/thegamecracks/thestarboard/tree/main/db/migrations
i just used the ERD feature of pgadmin because that was what i had on hand, the lines were quite finicky to edit
gotcha
so the user table
but basically i normalized the various discord entities (users, channels, guilds, and messages) into their own tables for the benefit of clear relationships and cascading deletes
(for example if the starboard channel was deleted, i have the guild config table set to nullify the starboard channel ID, or if a message was deleted any stars recorded for that message would be deleted too)
all u need rly
unless u want other fields such as avatar url, username, display (all accessible through using the id)
the disadvantage is having to make more queries when inserting entities to make sure their dependencies are present
https://github.com/thegamecracks/thestarboard/blob/main/src/thestarboard/database/api.py#L149-L152
src/thestarboard/database/api.py lines 149 to 152
await self.add_channel(channel_id, guild_id=guild_id)
await self.add_user(user_id)
await self.conn.execute(
"INSERT INTO message (id, channel_id, user_id) VALUES ($1, $2, $3) "```
so whats the reasoning for the table with just the id, you wouldnt be able to do much with that information in a table right?
well really the main reason was i just wanted to make a normalized schema to see how it would go, but in practical usage you might find denormalizing your schema (e.g. no guild/user tables) easier to work with
in my schema i have it configured so if say, the bot gets removed from a guild, it can run a simple DELETE query on guild to make everything associated with that guild go away (config, channels, and messages)
please just dont use on_ready
and also why do you need to close the bot afterwards?
and also please please do not spoonfeed code
generally you dont need to input the guild id, channel id, and message
i would recommend you read the examples first
How to get ratelimited 101
why
lemme explain
As noted in the docs, on_ready is also triggered multiple times, not just once
discord.py
examples can be found in the message linked above
you dont
yea but he didn’t wanna use commands so would have to be that or presence probably
bruh why do you have the token to begin with
How do you have dynos token?
still on_ready should not be used
- Before even attempting to create a discord bot, please learn python (
!resources) - To install discord.py, please run
python3 -m pip install discord.py(linux), orpy -3 - m pip install discord.py(windows)
If you wish to use voice functionality, please usediscord.py[voice]instead ofdiscord.py - Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
- When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f - The library documentation is available at https://discordpy.readthedocs.org/en/latest/
If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py
If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html
anyways
see this
np


