#discord-bots
1 messages · Page 316 of 1
All
Like
If they join but yet not passed the verification, they won't be able to use my emojis
how can i add slash commands to my bot?
here's an example and brief doc about it for dpy https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
well if it's the emojis in your guild, you can set em via Emoji.edit and exclude the everyone role in roles kwarg
And only ones who have @ member (role given after verification) permission or higher will be able to use emojis from my guild on other guilds?
noe
okay
yes, just include those roles by guild.roles[1:]
since guild.roles always contain everyone role, and it's the first element, you can slice it
i dont mean
External emojis on my server
I mean
My emojis on other servers
pretty sure if they dont have the role in your server it wouldnt work on other server as well
i forgot though so i cant test
how can I make my bot an authorized app?
What do u mean?
Like this
I only found this https://discord.com/blog/the-future-of-bots-on-discord
There is a Verified Bots topic
But dont say any requirements
I saw also that for a bot that is in more than 100 server it has to be verified to get in another one
there isn't anything to show, i just need a way to make a url where it contains the bytes of a image or use some other method for again using bytes on a avatar
like if u wanna the read process of how im getting the bytes, ig here
#...
async def foo(attachement: discord.Attachement)
contents = await attachement.read()
# Processing...
return contents
# When they want to execute a specific command
async def bar(data):
# Making the webhook
avatarBytes = ...
# Processing...
await webhook.send(avatar_url = avatarBytes) # Or some other method that i don't know for creating a avatar
Authorized Apps are just a list of discord applications that you have given access to information about your account, which is done through oauth2:
https://discord.com/developers/docs/topics/oauth2
Yeah so my quedtion was. How to Make it
what for?
afaik you can't selfbot using oauth2
I have no idea
For Dashboard
discord documents it's oauth flow how it works is u create a callback url in bot app which points to url in ur website and get users acess token and refresh token and use those to validate requests
Asher writing a paragraph
one para not enough to document discord oauth flow 💀
that's why they have a whole page of documentation for it
trenything is possible
from discord.ext.ipc import Server
In a tutorial he use this. But i use nextcord. How is it called in nextcord?
its a thirdparty module no?
what library is the tutorial using?
why would it even exist in python discord
i have no idea haven't done discord bots in a while
better-ipc
bruh
bro write your own implementation 💀
u probably don't want to use pure python for a dashboard either
at best for backend api
challenge accepted
sure hab fun you have to resort to js for a lot of front end interactivity either ways
did I not say challenge accepted
how would you even interact with a dashboard written in react with a bot written in python
xd
thats another challenge tbh
write data in text file
apis
bro in ideal case you would have a common db between bot and website
just the db?
it wont solve your all problems tho
hmm maybe we can store bot token in both side
depending on what data you want ideally the data can should be fetched based on scopes you asked for that can be done in website itself
yeah then just need to store the bot token?
if you want data outside scope make endpoints or run a webserver along with your bot
depends on how you structure your project
if the data you need is not present in scope then sure
iirc for plain oauth u dont need bot token right?
no, but yk you gotta list all servers that bot is in in mutuals of that user xd
finally
guild scope is there for that right
Why?

nah I was already lost when I saw discord.ext.ipc
fair
Can someone enlighten me xD
nah bro you enlighten me first
is ipc already just your 3rd party lib
yeah that doesn't tell me none
what are you planning to make your website in?
Make a Dashboard for my Bot
js, python etc what are u familiar with
Python and html
do you have a db?
Yeah
so pick some library like django or fastapi
I have fast api
uh? anyone?
looks like uploading bytes is only supported during the actual creation of the webhook, but if you're already getting the image as a discord attachment, you can give the attachment's url as the avatar
oki dokie
it kinda raises a problem
since i need the bytes to recustomise the webhook's avatar
i don't have a attachement
i only have the bytes of it
Can you do it similarly to embed's attachment:// way? I wonder
Flip the arguments around in your button callback:
(button, interaction) -> (interaction, button)
Question, does anyone know if you can make your bot use an app command from another bot?
or would that be against ToS..? or is that even possible?
Not possible due to Discord limitation
Nope
Most bots don't let other bots interact with eachother either way, so 🤷
Error is extremely clear
I also don’t see why you’re awaiting an append method
Is that possible? to have a boost channel? kinda like a welcome and leave message?
if so, whats the docs for it
When I deleted it
It will say it's not awaited
Yes it's in your server settings
im talking about discord bots, not for discord
embedding looks better compared to what discord does :/
What's the problem, then? You just send the embed to whatever channel you want
what event would it be?
we have on_member_join an on_member_remove now what about something like on_member_boost or something? which i know on_member_boost isnt a thing, so wondering a way to do it..?
It's just an on message
I need the docs for how it detects a boost :/
just note that the .type attribute has to be MessageType.premium_guild_subscription
@bot.listen("on_message")
async def on_boost(message: discord.Message):
if message.type != MessageType.premium_guild_subscription:
return
print(f"{message.author} just boosted {message.guild}!")
Okay, ty
What is initial_extensions
I don’t see why it needs to be awaited
It looks like a list
so ive gotten myself in a bit of a rut here.
Im trying to disable commands per-guild IF the guild has not been configured. My idea was to use before_invoke and stop the command from completing there. I just cant seem to stop the command from executing though. Any ideas?
I was following this
https://youtu.be/rWfrdBAinvY?si=BsOS7awb_RPwPLDB
Adding Cogs to your Discord Bot is one of the best things you can do. It transforms your Discord Bot and Python code into something that is undoubtedly better via the use of Cogs.
It allows for all of your commands and events to be organised into corresponding sections which means that it's a lot easier to read and understand the Python code f...
Or you could just answer my question…
@final iron Do you have an input for this? Been stuck on it for a while
Are you disabling specific commands or all commands?
I would like to disable all commands. But my current method was just to disable the invoked command in before_invoke
You can override the on_message event to only process the commands from the guild messages if it's in a list or whatever you're using to configure it
Ah, never thought of this. Ill look more into it and come back once ive gotten some results
Thank you
🐈
what if the server has disabled the boost message
hey i am trying to do cogs but i cant really make it work
this is my main code:
import settings
from settings import *
import discord
from discord.ext import commands
from discord import app_commands
import os
import string
import random
import asyncio
intents = discord.Intents.all()
intents.messages = True
intents.message_content = True
client = commands.Bot(command_prefix='.', intents=intents)
@client.event
async def on_ready():
print(f'{client.user.name} is running')
try:
synced = await client.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
client.remove_command("help")
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run(BOTTOKEN)
this is my command code:
import discord
from discord.ext import commands
from discord import app_commands
import random
class coin(commands.Cog):
def __init__ (self, client):
self.client = client
@commands.command(name="coin", description="Flip a coin")
async def coin(ctx, choice: str):
choices = ["Heads", "Tails"]
if choice not in choices:
await ctx.send("Please choose either 'Heads' or 'Tails'.")
result = random.choice(choices)
embed = discord.Embed(title="Coin Flip", color=discord.Color.gold()),
embed.add_field(name="Your Choice", value=choice, inline=False),
embed.add_field(name="Result", value=result, inline=False)
await ctx.send(embed=embed)
def sutup(client):
client.add_cog(coin{client})
TIL
but now that I think of it, it make sense
useless ping sorry kek
?
sutup
Pointless to set messages and message_content to true as well if you already have intents set to all()
saw that got it working
And look at coin{client} again
And you should upgrade the library version, it's outdated
maybe yes
i think ik one unefficient and obvious solution
since i can't change the actual webhook's image. il just create a brand new webhook and delete it per iteration
i think it might work
but its really inefficient
i just wish i could input the bytes instead
for changing and not creating and deleting
nvm
i found a function and its webhook.edit
So, when a bot does botname is thinking... an its animated, do you have to have your bot verified for that? Or how do they make it animated n stuff?
For example for Mee6 it would be Mee6 is thinking...
error doesnt match the code
full error:
error still doesnt match the code, did you make sure to save the code before running?
yep defo saved
error defo does match the code
now it's updated
Member is Guild specific, so you may try typehinting to discord.User instead
oh nvm they translated to the same thing in slash
??
when you do user: discord.Member, you're trying to get a member that is in the guild which makes no sense because you're unbaning them, they are not in the guild
yes, typehint it to str and then use discord.Object, ```py
async def unban(interaction: discord.Interaction, user: str):
await interaction.guild.unban(discord.Object(user))
oh ok
alr worked thank you
alright welcome
yeah but in the on_approve def, i want it to add a role to the member that passed the application. To do that i didawait member.add_roles("Waiting for Interview")
but "member" isnt defined
you have defined it but its in another class
i tried to define it in the on_approve def as member = interaction.user but the bot think that member is the user that interacted with the approve message
you completely missed the point of that example, you can access the member by self.member
see how the data flows through from 1 class to another
ΟΗ
essentially, ```py
role = discord.Object(ROLE_ID)
await self.member.add_roles(role)
Try it
ok
!d discord.Interaction.user
The user or member that sent the interaction.
i also need the bot to send to the channel the application that the user submitted
so the manager knows what he answered
to approve or to decline him
Hi, so i found this code on github:
https://github.com/DorianAarno/Minesweeper-Discord-Bot/tree/main
and i tried to update and change to code from disnake == 2.3.2 to discord.py, and if you have helped me before and remember me then you know it went very very bad.... so my code and error is in the sourebin down below:
https://sourceb.in/7q7c2LEnde (code)
https://sourceb.in/D7fq0NU7vR (error)
I dislike the naming already 🫠
oh dw i am trying to transfer that code from disnake to dpy
ps i told clearly thats not my code 😂
is httpx has blocking on discord.py like requests?
well
interaction.response is a discord.InteractionResponse object
and interaction.command is an app command object
ok
you need to access their attributes to get useful info for logging
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response).
New in version 2.0.
Thank u
you can but @fiery cairn
htppx supports async too https://www.python-httpx.org/async/
if you use the asynchronous interface then it'll be ok
A next-generation HTTP client for Python.
!d discord.app_commands.AppCommand.name
The application command’s name.
thanks
to get the name of the command
you can check the docs for these things
here there are all the available public attributes for the objects
But so how do I also send the output?
wdym? the output of the command?
Hi, so i found this code on github:
https://github.com/DorianAarno/Minesweeper-Discord-Bot/tree/main
and i tried to update and change to code from disnake == 2.3.2 to discord.py, and if you have helped me before and remember me then you know it went very very bad.... so my code and error is in the sourebin down below:
#error
STARTUP /home/container: ${STARTUP_COMMAND}
File "/home/container/temp.py", line 1087
def __init__(self, ctx, custom_id, label="", bombs, board):
^^^^^
SyntaxError: non-default argument follows default argument```
code:
https://srcb.in/mAFDbrTA4Q
!e read the error
# valid
def a(arg_one, arg_two): ...
# valid
def b(arg_one, arg_two=""): ...
# invalid
def c(arg_one="", arg_two): ...
@naive briar :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 8
002 | def c(arg_one="", arg_two): ...
003 | ^^^^^^^
004 | SyntaxError: parameter without a default follows parameter with a default
ik, and i am stupid; please explain me...
Explain you? 
tbh i dont know why add this restriction 
Hiii
2023-10-25 16:29:29 ERROR discord.client Ignoring exception in on_member_update
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 392, in on_member_update
cursor.close()
File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/cursor_cext.py", line 495, in close
self._cnx.handle_unread_result()
File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 961, in handle_unread_result
raise InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found```
@bot.event
async def on_member_update(before, after):
guild_id = before.guild.id
connection = mysql.connector.connect(host = '', database = '', user = '', password = '')
cursor = connection.cursor()
query = "SELECT channel_id FROM log_moderation WHERE guild_id = %s;"
cursor.execute(query, (guild_id,))
row = cursor.fetchone()
cursor.close()
connection.close()
if row is None:
return
channel_id = row[0]
channel_send = before.guild.get_channel(channel_id)
if len(before.roles) < len(after.roles):
newRole = next(role for role in after.roles if role not in before.roles)
if before.roles != after.roles:
embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
embed.add_field(name = "Role added :", value = newRole.mention, inline=False)
embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
await channel_send.send(embed=embed)
elif len(before.roles) > len(after.roles):
oldRole = next(role for role in before.roles if role not in after.roles)
if before.roles != after.roles:
embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
embed.add_field(name = "Role removed :", value = oldRole.mention, inline=False)
embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
await channel_send.send(embed=embed)```
Can you help me please, i have never get this error before and i don't see any error here
Swap the positions of the button and interaction parameters in your button callback
It's just confusing
what confusing? 
What if you want to set c without setting b first?
def a(\, b=0, c): ...
i mean now the args are positional only it makes sense here
but what about nothing, no * or no /
wait its a back slash 
Since then there will be no restrictions on how the caller provides the arguments
It's probably get confusing for the interpreter
*It'd
hmm, fair
Then I'll put c before b 
Sure 
Hover over it
Also what does this have to do with discord-bots
Dashboard
Category?
Other and Web Development probably
@hybrid_command(name="announce", description="Отправить объявление от имени бота в указанный канал.", with_app_command=True, help="Отправить объявление.", nsfw=False, hidden=False, brief="Объявление.", usage="!announce <канал> <объявление>", guild_only=False, enabled=True)
@commands.has_permissions(manage_messages=True)
async def _announce(self, ctx: commands.Context, channel: discord.TextChannel, *, message: str) -> Message:
"""
Отправить объявление от имени бота в указанный канал.
Parameters:
ctx (commands.Context): The context of the command.
channel (discord.TextChannel): Канал, куда отправить объявление.
message (str): Сообщение, которое нужно отправить объявлением.
Returns:
discord.Message: The message sent by the bot indicating the result of the operation.
Raises:
Exception: If an error occurs during the execution of the command.
discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
commands.MissingPermissions: If the bot is missing permissions required to execute the command.
"""
try:
if channel is None or channel not in ctx.guild.channels:
return await ctx.send(embed=discord.Embed(description="Укажите канал, куда отправить объявление!", color=discord.Color.red()))
if message is None:
return await ctx.send(embed=discord.Embed(description="Укажите сообщение, которое отправить объявлением!", color=discord.Color.red()))
embed = discord.Embed(title="Объявление", description=f"{message}", color=discord.Color.green())
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
await ctx.send(embed=discord.Embed(description="Объявление отправлено!", color=discord.Color.green()),ephemeral=False)
return await channel.send(embed=embed)
except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
return await issue_msg(e, ctx) # Handle any exceptions that occur during the execution of the command
how to handle the fact that the user does not specify anything in the chanel and message arguments when using the !announce command (not /announce)
Set a default value to None, or ask the AI you've already asked
I specifically removed `None' so that when using the application command, arguments are mandatory
And what makes you think I stole the code?
It's fairly obvious.
Anyways, you can check the value these parameters have if you don't provide them in prefix commands, and then compare these in the future
damn, that's a new one
how to make a discord bot 101 2023 no fake 100% working
might want to check
https://discordpy.readthedocs.io/en/stable/quickstart.html
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.
No module named 'bot'
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.
```py
```
This still doesn't answer the question
What is bot
No?
This literally doesn't answer my question
What is bot. Is it a local file, module etc
just replace your token in this file, and run through it...?
Could you show your file structure?
No
Shift + windows key + s
It'll be saved to clipboard and you can paste it in
???
import discord
TOKEN = ''
bot = discord.Client(commnds_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'{bot.user} is now running!')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f"{username} said: '{user_message}' ({channel})")
bot.run(TOKEN)
lol
How to make bot 101
a. Enable all intents, very important
b. Make sure to name your bot variable client, and alternatively your client variable bot
Oh and
c. Make sure to str() everything, and then use f-strings so that it's done twice
simply
Can anyone help..?
No
Why?
Why would discord restrict thinking events to verified bots only? A user typing isn't really a privileged event
Yeah, you say that but it's kinda a yes or no question, then explain how to do it, but you avoid what I'm asking... just wanted to know if it needs to be verified and how to do it..
that thing can be setted with a kwarg on InteractionResponse
No
Why?
Why would discord restrict thinking events to verified bots only? A user typing isn't really a privileged event
And you've already been told how to do it in the discord.py server
So I didn't see the need to repeat it
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
I do both servers to make sure..?
Cuz sometimes they give a different point of view that's why..?
Or explain it differently.
I mean the docs explain it all
And I don't see why there would be a different point of view as it's just True/False being passed to a kwarg
There really isn't any other way to do it
I mean I've gotten 2 different point of views multiple times
This is literally the only solution
Yeah, but I didn't know that, I wanted to make sure 😭
Sure, but there's absolutely 0 reason to call me a dick
I already explained why..
This?
From my pov it just seems like you were being a dick, sorry I called you a dick, but from my pov it just looks like you were.
You asked a question, I answered and then clarified
I'm talking abt before :/
Like I said, I'm sorry, but from my pov it just seems like you were trying to be a dick.
And that was wrong
Just avoid calling people dicks in the future, for any reason really
I mean I could say worse 😭😭
But I have no reason, and no one should tbh, but like I said, I am sorry for calling you a dick.
Hi im having trouble whit a leave longing system. When i leave the server the on_member_removed event docent respond to the event
Code:
def add_score(member: discord.Member, amount: int):
if os.path.isfile("./data/Leave.json"):
with open("./data/Leave.json", "r") as fp:
data = json.load(fp)
try:
data[f"{member.id}"]["score"] += amount
except KeyError:
data[f"{member.id}"] = {"score": amount}
else:
data = {f"{member.id}": {"score": amount}}
with open("./data/Leave.json", "w+") as fp:
json.dump(data, fp, sort_keys=True, indent=4)
def get_score(member: discord.Member):
with open("./data/Leave.json", "r") as fp:
data = json.load(fp)
return data.get(f"{member.id}", {}).get("score", 0)
def in_channel(*channels):
def predicate(ctx):
return ctx.channel.id in channels
return commands.check(predicate)
@client.event
async def on_member_leave(member):
await add_score(member, 1)
print("Leave")
on_member_leave doesn’t exist
oh is on_member_removed then?
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) leaves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
If the guild or member could not be found in the internal cache this event will not be called, you may use [`on_raw_member_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_member_remove) instead.
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
Search feature is pretty useful
Tnx
How can you prevent users from spamming others DM on your Discord server?
actively checking security tab if it have say suspicious dm activity
if there are, just turn off dm for 12 hours
*if there are a lot
Is that even available for bots
i dont think so
So…
but I don't think anything else can prevent spam dm
This is discord bot channel. It’s pretty obvious he wants a programmatic solution
how do you programmatically prevent spam dm when the bot don't even know there are dm
It’s not possible
yeah exactly, so I tell him the only possible solution
The whole point of having a bot is to automate tasks
Manually doing something like this, especially if it’s a security bot isn’t feasible
except discord doesn't make an API for it, how terrifying
Yeah, so it’s not possible
yeah, not possible with bot
That’s the whole point
and seriously discord should do better at this
at least make an API, it is not that hard
There's currently a lot of features missing from the bot API
yeah
Considering bots were, and still are the backbone of discord's ecosystem I don't understand why
like when start typing is an event call, why not stop typing is an event call as well
Up until around 2 years ago it was extremely difficult to moderate exclusively through discord
Impossible for large servers
If there was raid and you didn't have a bot, then you would have to close the entire server manually
If you weren't there to do it you were SOL
like when you try to make it easier for human to moderate, why not make bot easier as well
bot is way more effective
I'm trying to iterate through all the server roles in a command to appear as options.
Ive been stuck on this for a good time now, any solutions?
yeah, literally if you marked flag on user on suspicious dm event, why cannot bot know it and do action automatically
you can literally put discord.Role as input field
damn
and it will have all the role listed
For starters, discord.Interaction is a class
in discord way
https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type
These types can be translated to Python or discord.py types and used as typehints for slash commands.
STRING ->
- str
- app_commands.Range[str, min_length, max_length]
INTEGER -> does not support IDs
- int
- app_commands.Range[int, min_value, max_value]
BOOLEAN -> bool
USER -> in a guild, you will receive a member regardless of typehint, but it will not have presence data
- discord.User
- discord.Member
- Union[discord.Member, discord.User]
CHANNEL -> Union containing any number of these types is supported
- discord.Thread
- discord.abc.GuildChannel - all below
- discord.CategoryChannel
- discord.ForumChannel
- discord.StageChannel
- discord.VoiceChannel
- discord.TextChannel - text, news
ROLE -> discord.Role
MENTIONABLE -> Union with any combination of USER and ROLE
NUMBER ->
- float
- app_commands.Range[float, min_value, max_value]
ATTACHMENT -> discord.Attachment
Notes:
Rangebounds may beNoneto remain default.
Minimum and maximum values can be found in the option structure above the list of types.Transformercan be used for any types not listed above.
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Transformer- Parameters can be made optional by giving them a default value or typehinting as
typing.Optional[X]orX | None
yeah
way more detailed
guild is simply a property as discord.Interaction hasn't been initalized
Nope
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.
nvm missed the R
@final iron are you good with working with mongo DB?
ah alright
perhaps #databases would be a more ideal place to get help with Mongo
is discord.py easier then discord js? I have more experience in python
Whichever language you have more experience in will be easier
Not really. It's about the same level of difficultly, just in a different way
Hi, so i found this code on github:
https://github.com/DorianAarno/Minesweeper-Discord-Bot/tree/main
and i tried to update and change to code from disnake == 2.3.2 to discord.py, and if you have helped me before and remember me then you know it went very very bad.... so my code and error is in the sourebin down below:
https://srcb.in/TFuckExYRJ
async def callback(self, inter):
assert self.view is not None
view = self.view
await inter.response.defer()
if inter.user.id != self.ctx.author.id:
return await inter.send("You cannot interact with these buttons.", ephemeral=True)
b_id = self.custom_id
if int(b_id[5:]) in view.moves:
return await inter.send("That part is already taken.", ephemeral=True)
if int(b_id[5:]) in self.bombs:
await view.RevealBombs(b_id, view.board)
first of all if you are using discord.py there's no .send in Interaction iirc instead use
await inter.followup.send(...)
if len(view.moves) + len(self.bombs) == 25:
await inter.response.edit_message(view=view)
await view.EndGame()
await inter.response.edit_message(view=view)
you have already responded with the interaction using defer, to edit the message again consider using
await inter.edit_original_response(....)
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
how do I make a button view that never expires
A button never expires
It expires when you restart the bot
I want it to work even if my bot restarts
you have to make persistent view
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
then use this to add the persistent view when bot starts
and for making a view persistent, you must pass timeout=None in the view and set a custom_id for every childrens in the view
So I am specifying the userid on the custom_id when I create the view like this quit:userid where I want to check if the user's id who clicked the the button is same as userid, how do I implement this in presistent view?
Is there a way to connect 2 clients in a single script?
Yes
How?
Use asyncio's tasks system to start the clients by their client.start method
Either by asyncio.TaskGroup (python >= 3.11) or asyncio.gather or even manually creating and awaiting the tasks
How would that work?
!d asyncio.TaskGroup take a look
class asyncio.TaskGroup```
An [asynchronous context manager](https://docs.python.org/3/reference/datamodel.html#async-context-managers) holding a group of tasks. Tasks can be added to the group using [`create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task). All tasks are awaited when the context manager exits.
New in version 3.11.
how do i make my discord bot automatically send a message as soon as a ticket is made by ticket tool
Thank you
async def main():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(client.run(token1))
task2 = tg.create_task(client.run(token2))```
Any idea why this isn't working?
Does anyone know how to make my discord bot responsive?
What do you mean?
Like making my bot respond to discord messages
@bot.event
async def on_message(msg):
await msg.reply("Hello World")
Is that what you meant ?
Yes, thanks
Np, btw you'll need to add another line of code if you want your bot commands to function:
@bot.event
async def on_message(msg):
await msg.reply("Hello World")
await bot.process_commands(msg)
how do i make my discord bot automatically send a message as soon as a ticket is made by ticket tool
@vocal rivet That's because the client.run is just a normal, not a coroutine (not awaitable basically). I told you to use the client.start that is awaitable
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect).
Oo ok
@naive briar
What?
Not working
You're not even running the main function you defined
Yes?
what's the decorater to mark a discord bot cmd as owners only cmd
RuntimeError('Event loop is closed')
!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.
paste this exact question in google, the first link has an answer.
u could have just told me the decorater instead of typing that shit. Just don't reply if don't wanna help
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner).
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner) that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Next time you can search yourself though - https://discordpy.readthedocs.io/en/stable/search.html?q=owner - it's not rocket science
Do someone know how can i make a uptime command ?
.
Save the time in a bot variable when the bot started
In the command get the difference between the time now and the saved start-up time
At the end of setup_hook, save time.perf_counter(). The command can call it again and subtract the saved time from it to get how long it's been since then in seconds
!d time.monotonic more like
time.monotonic() → float```
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use [`monotonic_ns()`](https://docs.python.org/3/library/time.html#time.monotonic_ns) to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float) type.
New in version 3.3.
Changed in version 3.5: The function is now always available and always system-wide.
Changed in version 3.10: On macOS, the function is now system-wide.
hey people.... one thing is
followup.send
but i want to edit my message.... what was the followup for edit?
someone tell me how to make buttons work even after restarting the bot?
on your on ready event; add your button class view (i might be mixing up the function name)
but like this:
lets say i have a button named as ratings i would do:
@bot.event
async def on_ready():
print("Bot is ready!")
bot.add_view(ratings())```
i have a lot of buttons
welll.... until what i know, thats the way.... or a big shot might or might not work:
add all the buttons in 1 class view (again i might be saying the wrong function name) and add that class view in the bot ready event
Anyone can help me with this?
@client.tree.command(description='Random decide team')
async def r_player(interaction: discord.Interaction, player1: str, player2: str, player3: str, player4: str, player5: str, player6: str, player7: str, player8: str, player9: str, player10: str):
players = [{player1}, {player2}, {player3}, {player4}, {player5}, {player6}, {player7}, {player8}, {player9}, {player10}]
random.shuffle(players)
Bravo = [players[0], players[1], players[2], players[3]]
Alpha = [players[4], players[5], players[6], players [7]]
Charlie = [players[8], players[9]]
embed = discord.Embed(title="Random Player picker(Private battle)", description= "Allow you to random decide team members")
embed.add_field(name="Team Alpha", value=Alpha)
embed.add_field(name="Team Bravo", value=Bravo)
embed.add_field(name="Team Spectator", value=Charlie)
embed.set_image(url="https://media.discordapp.net/attachments/971919486934478858/1167097215785906228/Private-Battle.jpg?ex=654ce2fb&is=653a6dfb&hm=01c0c477e30d8e7320a1edcecd24a41ee1bf03cd8a48e8efa374cfbd441e844d&")
await interaction.response.send_message(embed=embed)```
is there any way i can select which buttons to display on first line( or does discord chooses that by itself)
like i want to be able to show 1 button on line 1 then 2 buttons below it!
In persistent view how do I check if the user who clicked the button is same as the user who ran the command?
!d discord.ui.button
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
row=
store the data in a database
any recommended Bot hosting sites?
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
Digital ocean
awesome sauce
wdym?
alright listen up. I am attempting to build my own bot, I have decently good experience in coding in python so i want to use that, i boot up servral tutourials to see its all generally the same method Install Discord.py. ...
Create a Discord Application and Bot. ...
Create a Discord Guild (Server) ...
Add the Bot into the Server. ...
Code the Bot.
simple
so i boot up visual studio code (python ver. 3.11.6) and get to work
problem
its not connecting to the bot
Are you running the bot instance?
its just another way of saying "Okay."
And also - how would I time a command? Like, let's say I have
async def foo(ctx):
timer.start()
# some command here...
timer.end()
await ctx.send(some_result_here + "(executed in %s seconds)" % timer)
what sort of error are you getting?
well first it was basic syntax (missing 'intents' in such) but after i fixed that i keep getting certificate verification errors
im good but not that good, so i have no clue what this means
You shoudnt be doing this in on_ready, especially recommending it
ah, you have to put intents into your commands.Bot. So like, bot = commands.Bot(command_prefix=..., intents=discord.Intents.all()) or whatever intents you have enabled.
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead 🦀 GCP, AWS have one year free micros.
@velvet tinsel How would I time a command?
Use thetime.perf_counterortime.monotonic, for example:
import time
start_time = time.perf_counter() the
# do something
print(time.perf_counter() - start_time) # print the elasped time
You shouldn’t be using all(). Nobody needs every single intent. It’s a massive waste of resources
I can't edit or reply to messages, so you know
it's just an example.
oof, what happened?
Average Discord alpha bug
Doesn’t matter. People will take those examples and add it into their code without knowing the downsides
are you using the new version of discord?
thats exactly what i did, but the problem is the code is not connecting to the dev api for some reason
Is there an error
like the bot wont go online
@velvet tinsel probably
Doesn’t answer the question
I'd opt-out from it at some point
Uhh, well, if you send the ✨ emoji, click down on it to zoom in, and hold down on the enlarged emoji you should go back to default.
It's weird
and also- your code just kills the command for me 😭
I'll look into time.monotonic, though
Calling time.perf_counter shouldn't cause the application command to fail
It was caused by something else
there's no errors, it just... doesn't respond.
Using time.monotonic won't fix your problem
Have you applied an error handler to it to see the problem?
Anyone that knows a method to make buttons work even after restart? (Except for this method)
For future records, setup functions should be performed in discord.Client.setup_hook, not in that event
I think buttons are always attached to views, so that method seems the simplest. At least, simpler over #discord-bots message
Is that module part of discord.py?
It’s not a module…
No?
Anyone?
?
The SSL or TLS certificate verification failed
Up here
That's odd
Cause I’m not exactly fluent in connective Wi-Fi terminology
Or https for that matter
To begin diagnosing, have you downloaded any other packages besides discord.py using pip? It should be the only package you need to develop Discord clients/bots in discord.py
Many tutorials out there are outdated and use forks or alternative packages for features the current version of discord.py now has
I don’t remember installing anything else
That's not an issue that happens with discord.py that I know of
Are you using any other networking module?
I know discord.py uses aiohttp under the hood, so are you using aiohttp for other uses?
You know it might just be that
Using aiohttp isn't a problem in itself
I’m gonna go check rq
Using aiohttp to communicate over HTTPS and providing a problematic SSLContext is more like the problem you're having
You always need to provide a valid context for that purpose
No matter whether it is aiohttp or any other Python tool which does that
a full error message would be more useful, but if you happen to be on macos and the error message looks like "unable to get local issuer certificate", here's a tag commonly sent in the discord.py server:
Getting
[SSL: CERTIFICATE_VERIFY_FAILED]on Python 3 on OS X?
Navigate to yourApplications/Python 3.X/folder and double click theInstall Certificates.commandto fix this.
Happy coding!
they linked an official example of persistent views using client.add_view(), which ive also written a small guide for it a few days ago:
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
A short tutorial on persistent views in discord.py - 1-readme.md
They wanted a way without using client.add_view
Not possible.
alright, File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]"
yup, but i would recommend against attempting to handle message components manially
Tell them about it
You could store all the views in a sequence and loop over it, but you eventually would have to add it as a view
Handling it via events and such can be a cool thing to have in the package
aight looks like the tag i sent is appropriate for your situation
right
i mean you can do it right now with on_interaction, it's just very inconvenient
Then a handling system which sits on top of it for updating specifically
I don’t see why using an event is easier. It’s more messy, and it doesn’t really make sense
Callbacks are so much easier to work with
Event handling with callbacks is the usual way it works in discord.py, no?
thats what views are, they dispatch the correct callbacks based on the message ID + custom ID, although the lack of dynamic custom ID support is a limitation of views
Do either of these ID change without specifying a view as persistent?
What kind of OS has no trusted certificate store?
Oh it needs to be explicitly enabled for Python on that OS
err, views are normally used for individual messages so i guess that changes? however if you dont specify a custom_id for your component, dpy generates a random string for you
but you have to pass a particular custom_id in order to make the view and its components persistent
What does client.add_view do to keep a view persistent?
theres no fucking way im having difficulty with JSON files
Are custom IDs a concept of discord.py?
Like?
My bad
That's off-topic
Without it the client isn’t made aware it’s an active view
No, Discord
Does it implicitly trust the message provided by message_id to "keep the components state as last time" for the purposes of "using the same view after restart"?
In any case, this just means discord.py doesn't provide something like a PersistentView class to handle view changes neatly
for persistent views
Is there a setup_hook equivalent method for views?
Oh, I guess __init__ or something
Nah, that isn't called on add_view
Something that's called by add_view
Are custom IDs a concept of discord.py?
basically as part of discord's API, every component must have a custom ID which discord sends to your bot so you know which component on a message was used
https://discord.com/developers/docs/interactions/message-components#custom-id
What does
client.add_viewto keep a view persistent?
internally, discord.py manages a mapping of component callbacks
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ui/view.py#L531-L532
when you send a message, all the view's callbacks are registered with your client so the next time it receives an interaction, it can lookup the corresponding callback
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/abc.py#L1564-L1565
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/state.py#L741-L746
client.add_view()simply registers those callbacks in the same way:
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/client.py#L2716
Does it implicitly trust the message provided by
message_idto "keep the components state as last time" for the purposes of "using the same view after restart"?
yes, if you change a component's custom ID externally from your client object, dpy won't be able to lookup the correct callback
although in theory the exact parameters of those components don't have to be the same, i.e. if you were to change a button's style or throw away a few options from a select menu but you don't change their custom ID, dpy can still dispatch the view afterwards
In any case, this just means discord.py doesn't provide something like a PersistentView class to handle view changes neatly
i don't see why they need to? only your bot can edit the components so it shouldn't expect them to change out of its control
Oh I skipped over the first line about message components in the developer portal. My bad
Or, I guess, good learning for me
I thought they were something like message attachments which could be edited by other applications
Actually is even that possible
🤔
Possible. In any case, good to know
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 497, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 97, in on_ready
if not persistent_view_added:
UnboundLocalError: local variable 'persistent_view_added' referenced before assignment
def main():
bot = commands.Bot(intents=nextcord.Intents.all(), help_command=None, case_insensitive=True)
load_dotenv()
secret_file = json.load(open(cwd+'/bot_config/secrets.json'))
bot.config_token = secret_file["token"]
bot.cwd = cwd
ipc = Server(bot=bot, secret_key="lol")
StartUpDB()
##################################################################################################################################################################
# load all cogs
for folder in os.listdir(os.getcwd() + "/modules"):
if os.path.exists(os.path.join(os.getcwd() + "/modules", folder, "cog.py")):
bot.load_extension(f"modules.{folder}.cog")
# load detections
for folder in os.listdir(os.getcwd() + "/cogs"):
if os.path.exists(os.path.join(os.getcwd() + "/cogs", folder, "ghost_ping.py")):
bot.load_extension(f"cogs.{folder}.ghost_ping")
##################################################################################################################################################################
@Server.route()
async def guild_count(self, _):
return str(len(self.guilds))
@Server.route()
async def bot_guilds(self, _):
guild_ids = [str(guild.id) for guild in self.guilds]
return {"data": guild_ids}
@Server.route()
async def guild_stats(self, data: ClientPayload):
guild = self.get_guild(data.guild_id)
if not guild:
return {
"member_count": "Unbekannt",
"name": "Unbekannt"
}
return {
"member_count": guild.member_count,
"name": guild.name,
}
async def on_ipc_error(self, endpoint: str, exc: Exception) -> None:
raise exc
#########################################################################
persistent_view_added = False
@bot.event
async def on_ready():
if not persistent_view_added:
bot.add_view(TicketMain_One)
bot.add_view(TicketMain_Two)
bot.add_view(TicketMain_Three)
persistent_view_added = True```
A Python wrapper for the Discord API forked from discord.py - nextcord/nextcord
Are the line with persistent_view_added = False and the line with async def on_ready(): in the same file?
users can delete attachments from someone else's messages? i havent noticed that being a thing, only just suppressing embeds
To remove or replace files you will have to supply the
attachmentsfield which specifies the files to retain on the message after edit.
from: https://discord.com/developers/docs/resources/channel#edit-message
Never mind:
Other users can only edit
flagsand only if they have theMANAGE_MESSAGESpermission in the corresponding channel.
Yeah
Are they under the same function directly?
Ig yes
Are they both under that main function directly?
Not inside some sort of an inner function
Didnt i posted the code?
It won't raise that exception if this is the case
because you have the assignment persistent_view_added = True in your on_ready function, python assumes persistent_view_added is a local variable, i.e. a variable that only exists in that function
in other words, python is ignoring your persistent_view_added = False declaration, hence why python thinks the variable isn't defined when it tries running if persistent_view_added:
in your case, you need a nonlocal declaration to tell python that it should refer to the variable in main() instead: py def main(): persistent_view_added = False def on_ready(): nonlocal persistent_view_added if persistent_view_added: # now python knows to use the definition in main persistent_view_added = True see also: https://docs.python.org/3/faq/programming.html#faq-unboundlocalerror
I'm gonna need to see the entire function definition
Oh thanks. New learned stuff today. Thx 
not bad. you helped too thx 
I didn't know Python's variable declaration worked like JavaScript's let
I thought it looks for the name in the local scope and then in outer scopes until it finds or raises a NameError exception
But I didn't know it firstly checks whether it is assigned later on in the local scope
in python that's called a free variable, which is assumed if your function uses a variable but never assigns to it (hence why the first example in the earlier FAQ link works)
How should I pass the arguments now? just with None?
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 497, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 98, in on_ready
bot.add_view(TicketMain_One())
TypeError: TicketMain_One.__init__() missing 7 required positional arguments: 'guild_id', 'header', 'textbox', 'button_one', 'f_re', 'channel', and 'category'```
Python checking whether a function makes an assignment to a variable is news to me
err, usually whatever arguments you passed to the view before your bot restarted
I feel like some of these can be fetched from add_view's message_id argument
Not only one server has the view but many more
yup, thats the hard part
that's usually where a database comes in, so you can store whatever information is necessary to create your views with the same parameters as last time
Does your bot send tickets regarding different guilds and such, or does it suffice to get this information from the view's message?
I saved custom ids for the button as well as the message id and guild id
Is this enough?
iunno, can you retrieve the original arguments for each view's guild_id, header, textbox, button_one, f_re, channel, and category with just that?
Can you use these IDs to get all the information for all the parameters of the view's constructor?
if it's not possible or it would be unnecessarily complicated, you should either remove parameters that you don't really need and/or store the parameters that you definitely need in your database
remove parameters that you don't really need
to know on construction
I can use the custom id to get the message id and the guild id
No
Not yet
I can use the custom id to get ... the guild id
What about the rest of the parameters you pass into the constructor? There are seven in total,guild_idis only one of them
Is stored in a other table
But i can change it
Gime a sec
If these are stored in the database, you need to query that info, too, to add the persistent view. The question is whether they can be fetched after constructing the view so you don't have to do that
how do I add roles to a user using role IDs
Member.add_roles() accepts any snowflake, so discord.Object(1234) would be how you'd add a role to them with only the ID
(although usually you can use Guild.get_role() too if your bot's cache is ready and you have the guilds intent enabled)
thank youu
wait doesn’t it take a list
*roles denotes a variadic parameter, meaning it can take any number of arguments
await member.add_roles([discord.Object(123), discord.Object(456)]) would that work
err no, you have to either pass them as separate arguments (i.e. member.add_roles(discord.Object(123), discord.Object(456))) or unpack the list using the * operator: py snowflakes = [discord.Object(123), discord.Object(456)] await member.add_roles(*snowflakes) see also: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
oh okay, tyyy
Is there an example ? Should i Loop it for each Massage id?
An example for what about it? I talked about doing many things in that message
anyone know why this is happening?
why was my code deleted
or error lol
self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
Something wasn't awaited
Share your code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
i have code where i try to make my bot stay online by sending a message every thirty seconds and i think thats the issue
# staying online
async def stay_online():
staying_online = bot.fetch_channel(1166153894666186892)
try:
await staying_online.send("Staying online!")
except:
pass
schedule.every(30).seconds.do(stay_online)
while True:
schedule.run_pending()
time.sleep(30)```
OOOPS i think i found the issue
nvm
Bots stay responsive as long as they are run. There is no need to use them for this purpose, and it's certainly advised against when they're offline
yeah thats the thing my bot hosting server was on uptime for three days and the bot goes offline if no one is active on the bot
and i dont want it to go offline so it bothers me
and im trying to program something else
that uses the schedule package
so the bot needs to be online for it to work
You can take a look at Replit's template for a discord.py bot with a "keep alive" mechanism
It or something like it may work on your hosting server
if u can send me the link it would be appreciated but can you please tell me whats wrong here
I recommend setting your hosting server to not go offline every thirty seconds to begin with
nooo not the hosting server the actual bot itself like i check the console sometimes and it says stuff like "client reconnecting in 700 seconds"
Discord.py doesn't do this
idk why its happening to me then ¯_(ツ)_/¯
An output like "client reconnecting in 700 seconds" could only be logged by the program
If not by the program, who else knows you're running a client program?
thats not exactly whayt it says its like
"discord.client" with a big red "ERROR" next to it and it says that
the "ERROR" is to the left of it
im using https://bot-hosting.net
and their servers are pterodactyl servers
Seems like it's logging a scheduled reconnection as an error
yeah and it gives me warnings saying something about webhooks or sockets or wtv?
The only time I can think when this may happen is when the internet connection is problematic enough to cause disconnection
So discord.py tries to reconnect
This is a terrible host who iirc uses a shared IP
The other reason for being terrible is causing an unstable connection to Discord
If my suspicions are correct
?
what host should i use then
wdym uses a shared ip
Hosts with a shared IP address, as the name suggests, share an IP address for multiple hosted environments. You end up with the same IP address as other users, so if anyone makes the IP address be banned from connecting to a server, all of you will be banned from it
Usually, there's nothing you can do about it
wait so ur saying if someone ddoses the ip then my bot and everyone else with that ips bots will fail
Nothing except not contributing to getting banned by IP address
Correct
Well, I don't think communication using just the IP is denied. I think it's a combination of the IP + the port for your program, which is unique to you and isn't used by others
cause i want a free bot host that works
It's a problem when people attempt to DDoS Discord which then denies service to you all
No well-working hosting service is free
If it's not your personal computer, it's someone else's
does this work
Why do you need all this discord bot hosting
Why can't you just buy a normal VPS
It says "try for free"
I'm assuming it's a well-respected service
Unless it's a free trial which lasts forever
Maybe, but it might not be free forever
cause im broke
Then you have to live with what you've got
These "Discord Bot Hosting Sites" are generally more expensive than normal hosting services
then please explain whats wrong with this
Yikes
You don't need a third party tool for running periodic backgruond tasks in discord.py
from discord.ext import tasks
@tasks.loop(seconds=30)
async def keep_alive():
channel = bot.get_channel(1166153894666186892)
await channel.send("Staying online!")
Then, you need to start the task via keep_alive.start() on startup
or whenever you care to
It loops automatically every 30 seconds
so do i put in the keep alive function keep_alive.start()?
or do i do it like how i did the schedule.run stuff
The keep_alive task should never start itself
No
You need to manage startup functions in bot.setup_hook
can u show me how im a bit confused (im not a professional that much on python)
In your case, it's a matter of reassigning bot.setup_hook to an async def function
async def on_startup(self):
keep_alive.start()
bot.setup_hook = on_startup
bot.run(...)
can i put this on a on_ready function
You shouldn't run startup logic in that function
It's not its intended purpose
on_ready may be called an unexpected number of times, including never, once or more
ok so make an async function to keep the bot alive then make another function that starts the loop? and set it up with bot.setup_hook?
You reassign bot.setup_hook with an async def function which accepts the bot as the first argument. That async def function performs startup logic, which as far as I know, in your case, calls keep_alive.start()
That should get the loop going
It won't stop your connection to Discord from turning unstable though
So it's unnecessary to begin with
If you do settle for this hosting service, which you've been suggested using cheaper and more reliable ones, you won't be needing it even if it has a problematic internet connection, which it shouldn't as an advertised Discord bot hosting service
if it stays like that ill explore a solution
Discord applications rely on a stable connection to Discord. If that's out of the question because of the hosting service, use a different one
Under normal circumstances, you don't need a "keep alive" mechanism
So you're periodically spamming #1166153894666186892 for no reason
well i mean the host runs off of coins
and i got the cheapest plan
and it uses 20 percent cpu max 😅
Test Autocode without a "keep alive" mechanism
That's when you know it has suitable connectivity
ok thank you
Limited CPU usage like this is a con
You would get this from bad virtual private hosts
show your code
Do you have bot.setup_hook = on_startup like I spoonfed you?
Also, you have my condolences for using that for Python development in general
look ok vscode pisses me off when i develop my bot so im using vs
Let me refer to the official documentations
Better alternatives exist
setup_hook does not take any arguments
I didn't know it's a static method in discord.Client
I always subclass it so I can use it as a regular method
Replace bot.get with await bot.fetch
The channel either doesn't exist or isn't cached yet
😎
my only problem is this now
# tells us client is ready
@bot.event
async def job():
for guild in bot.guilds:
print(f"We have logged into {guild} as {bot.user}")
await console.send(f"We have logged into {guild} as {bot.user}!")```
oh wait bruh
You need to move this logic to on_startup
You might want to implement sending the message to console in an actual single message instead of many
Rate limits are a thing with Discord
And discord.py respects them
it happens when im debugging my bot sometimes i think
i use ethernet too with 400 mgb
nothing wow
@brazen raft
This is some basic python
Your function doesn't return anything, and you never called it
I've been spoonfeeding him for this
@slate parrot It's time to take your time learning Python thoroughly before stumbling on things like this
bro ive been using python for about a year now
doesnt mean im gonna know everything 😒
Obviously not, but calling functions is some pretty basic stuff
This means you haven't learned basic Python for over a year now
You never want to rely on others to write code for you unless you pay them enough money
And paying money for work is against this server's rules
ok bro
bro ur not spoon feeding anything the only thing u "spoonfed" is how to work with tasks with discord py
i am not that experienced in python been working with python for a year now doesnt mean that ur spoonfeeding me everything if u tell me how to do something if im doing it wrong
I'm here to help with the project and I've already spoonfed you about using the library
I cut the line with spoonfeeding you about Python in general
Here are learning resources:
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@brazen raft its been fifteen minutes and no socket interupptions or anything
wtv theyre called
so ye the code works
Good for you on finding a VPS with a stable connection to the internet
Although expensive
$19 for that host lol
Absolute scam honestly
You could probably get a 4 core VPS for like $12 a month
This one is dedicated
i prefer raspberry pis
Anyone knows if there is a function like on boost event? And if yes can anyone make a quick example
Tbh i didnt thought of that im in to much stress to think right , thank you 
yeah it's fine
we all do that
nah its the same host but except its been on an hour of uptime and it didnt give me a single interupption
It isn't the same host if the problem no longer occurs
yes it is
hello people
im not using a differnet host at all its the same server same host
Then having an unstable internet connection inconsistently is a sign of unreliability
bro its not internet connection the bot is running off of a server
its not running off of my computer
I have no idea what's going on
Servers are typically highly specialized computers
Failing to work with the international network is a big fat L
Though not unheard of and there are cases where this isn't necessary. Not in this case though
basically i wanted code so that my discord bot could stay online cause if no commands are ran and it idles it goes offline and keeps trying to connect back to discord but it cant i use a terrible host
Try Diva Hosting, they are free. And online 24/7, if you're only wanting to keep it online
hm ok
No, don't recommend that
Considering their billing page doesn't even work due to a cloudflair issue I can't imagine it's a good host
Also this is like exceptionally bad
"free hosting" does not exist outside of free credits
Everything will be trash
I don't understand how you don't have the 4 euro a month to pay for an actually good VPS
I've used it for the past 6 months, always been online, always fast, always worked
!d discord.Member.premium_since tbh please dont recommend this to users who want to invoke a custom boost event instead recommend this
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.
in on_member_join event
How to check what the guild that user joined to cuz the bot in mor than 1 server
Show code
ok
Where is the error , like line?
And consider using powershell to run python, the python shell doesn't support colored output I guess
i dont know
how do i find that
Line 327. You are passing check=check but you don't have anything named check
Learn python before creating bots ¯_(ツ)_/¯
so what shall i do
Create that function and make there anything you need
how do i do that
im stupid
def check(...):
...
where shall i put that
In your code. And it's example function because i can't know what you want to do inside.
This is the output of seeing a random discord bot making blog on Google 💀
Or not learning python first
Surely second
But it can be combined with first :D
Tbh I daily see atleast such 4-5 people
I would recommend them to learn python properly and then they are open to make discord bots
some more help theres cleary a config.json file and it says it cant open
when i try run it
The file not exists
If you wana create it , then open it with w mode
or r+
It exists (i can see it in the left), but the path to it is incorrect i guess
The path to the file should be from the current working directory.
it works when i open it with python power shell
oops not seen , there are so many files lol
yep
Btw which extension you using for seeing such error?
Try correcting path
by doing
how do i do that
from the main.py file
So you running from this directory , right?
yes
And config.json is in this dir? Or in any sub dir?
it is in that dir
it's inside the Receipt Big Bot
Ok
i am confused i guess
Try running your code from receipt big bot folder
bc he couldnt be asked to pay for hosting
how do i do that
Bro learn some basic commands
Like
cd
just cd into that folder and run the main.py file
Do you know about running python files?
You should revise I guess
ye
Then try making bot
how do i run the file
hmm
which?
On vsc?
no
where then
python main.py
maybe py main.py
python main.py
There is run button in vscode also
yea its python <file dir>
ye but when i click that it show this error
press tab if you don't wana write full path 😂
oh i wonder what u gotta do then
I already told you about it
ye
Its a path issue
and how do i fix that
how do i open with w mode
discord.py docs
Okay
i recommend not to look into blogs on discord bots
right click on config.json and click copy path
Actually that's not main problem, he doesn't know python properly 💀
https://fallendeity.github.io/discord.py-masterclass/
Try checking out this also , it's a good tutorial
A hands-on guide to Discord.py
