#discord-bots
1 messages · Page 662 of 1
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
yes
You referring to that?
im gettting it from a RawReactionActionEvent
ill try it with that
thx
disnake.utils.get(bot.get_all_members(), id=payload.user_id)
like this it doesnt work
i mean try it and see
I don’t understand why people use it utils.get if they have an id
Iterating unnecessarily
yes
idk why i did it
agreed, you should only use get() func to search for names in an iterable
or to get channels
you need a dict, not set on the $set one
from cache
ohhh
so instead of $set i put what
a dict
thought so
{'$set': {'key': value}}
the same with not using f strings xD
ctx.message.author doesnt work in slash commands for some reason, how can I get the author then?
what lib r u using
u have an interactionevent (probably)
but f strings are necessary to format them though?
its better then .format and "sth" + variable + "sth"
of course it is
u dont use f strings?
i never said that, what made you assume that?
but f strings are necessary to format them though?
great news, i only get 2 errors now
yeah, necessary meaning it needs to happen in some cases
👍
yes but its very rare
!unbound
you defined level before
😂 that command is working very good xD
i did?
use the global keyword on level
yes
!botvar when
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
bad.
global level right
yes

Hi icy
why do so many ppls use dpy
Because it’s good
But really though, why make a bot variable when your only gonna be using the variable in a function and no where else? just useless imo
its good as base for a wrapper
I just like bots
e.g disnake is dpy in better
same
hi
in better 😭
y am i getting syntax error
bruh
@client.command()
@has_permissions(administrator=True)
async def restart(ctx):
if ctx.author.id == 315485035320836096:
shutdown_embed = discord.Embed(title='Bot Update', description='I am now Restarting. See you later. BYE! :slight_smile:', color=0x8ee6dd)
await ctx.channel.send(embed=shutdown_embed)
await client.logout()
else:
errorperm_embed = discord.Embed(title='Access Denied!', description='This command is `OWNER` only. You are not allowed to use this. Try not to execute it another time.', color=0xFF0000)
errorperm_embed.set_footer(text=ctx.author)
await ctx.channel.send(embed=errorperm_embed, delete_after=10.0)```
like this it should work
ty
^
but why do u use client and not bot?
also im new to this so it might be like the stupidest mistake lol
and shouldnt it be @commands.has_permissions()?
what are u trying to do?
i did what kayle told me but its giviing me syntax error
oh
put it where you use the operatorpy global level level += 5 or you could just define level in the function
my brother told me to do that but i didnt listen to him smh
and why make it global when you're using it in a function and nowhere else
not level >= 5?
oops I havent replied
.
ok its not showing
bugged
or what is he trying to do
i edited my message the moment you sent that
no idea, im just copying his code
yes
oops
no
what else?
im tryna add 1 to the current value of level
wait i could just do level= level + 1 right
yes
BRUH
level += 1
``` easier
if level is a integer yes
ye it is
that works?
saves 5 characters
of course
nah nah its all cool
!e
a = 1
a += 1
print(a)
@visual island :white_check_mark: Your eval job has completed with return code 0.
2
would like to have ++ in python tho
oo like in js
yeah
and in cpp
a discord mention is <@&id> lol
i dont know the @ and | but I think | is for typing
whats ~
what the hell is >> or <<
idk
bit shift
no idea
u can do pip show module tho
lmao
found it

Hm?
it doesn't take any positional
use the name kwarg
can someone help me
the guy who was doing the tutorial doesnt seem to get the error even though im pretty sure i didnt write anything different comparing his
can i do that with member too?
get_member doesnt exist
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
try use .value attribute
where
db[...].value
alright lemme try
the first argument you passed
ok
Hi it worked, the bot responds now
but the thing is
the guy created a $new command that adds new responses to the database
so when i do the $new command, it gets added..thats working
the guy also created a del command that removes responses added by users in the database
when he runs the del command...the bot responds like this
help? ```py
@client.command()
@commands.has_permissions(administrator = True)
async def restart(ctx, seconds:float):
await ctx.message.delete()
embed = Embed(title = "OFF", description = f"{ctx.message.author.mention} turned off me for {round(seconds)} seconds", color = Color.red())
await ctx.send(embed = embed)
await client.close()
sleep(seconds)
await client.connect()
embed = Embed(title = "Turned on", description = f"I came back after {round(seconds)}", color = Color.green())
await ctx.send(embed = embed)
i have all the perms
he does $del 0
and bot responds
['command 1 added by user', 'command 2 added by user']
when i do the same thing, the bot just responds []
anyone help?
!positional-keywords
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
which hosting are you using?
replit
ok
i get this error but he doesnt
?
Why do I get this error?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'content'```
```py
# This is my code
@commands.command()
async def Annoucement(self, ctx: Context):
print(ctx.content)```
It says it in the error
But on my second command it's work.
Does it print?
Yes.
You can just do print(ctx) that would work iirc
how did you invoke the command?
ctx.message.content
.restart
if that's what you mean
@visual island @slate swan Thanks, and sorry for ping.
You didnt add the positional arg
yes, you need to do .restart 10 for example
^
oh ok
In this case it should be a float
I have always used manual loading of cogs, but now I'm having way too many of them to load (everytime when I make one I have to add it to list and it is becoming unreadable) so how could I implement the loop thing
it would be helpful so I can restructure my files again
!d os.listdir
os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
Wait, I thought u already used os.listdir Nipa
so smth like this I would assume ```py
for filename in os.listdir('cogs_folder_or_smth'):
if filename.endswith('.py'):
#load the extension somehow
Yea
never have I ever used it, except once
what if I have like really many of folders?
Do I just need a multiple one of those loops
No
it will search inner folders as well?
dir = ?
├───cogs
│ ├───moderation
│ │ └───__pycache__
│ ├───other
│ │ ├───antimusicbot
│ │ └───__pycache__
│ └───__pycache__
``` if I have structure like this? (antimusicbot cog kicks music bots from guild because why not)
I dont think it will loop through the inner files
so I have to make a loop for moderation folder and for the other folder?
os.walk(top, topdown=True, onerror=None, followlinks=False)```
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory *top* (including *top* itself), it yields a 3-tuple `(dirpath, dirnames, filenames)`.
ext = []
for filename in os.listdir('cogs_folder_or_smth'):
if filename.endswith('.py'):
ext.append("the files")
for filename in os.listdir('2_cogs_folder_or_smth'):
if filename.endswith('.py'):
ext.append("the files")
bot.load_extension(ext)
``` I was thinking of smth like that if this makes sense
would this make sense, for me it does.
what's the use of the second loop?
I suck at nested loops, well actually in everything that is nested
for filename in os.listdir('cogs_folder_or_smth'):
if filename.endswith('.py'):
ext.append("the files")
for filename in os.listdir('2_cogs_folder_or_smth'):
if filename.endswith('.py'):
ext.append("the files")
``` might be like this if nested?
for folder in os.listdir("cogs"):
for sub_filename in os.listdir(f"cogs/{folder}"):
...
yeah sure
but in the ext you need to append as "cogs.subfolder.filename" not just the filename
help
client.command()
async def contribute(ctx):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
embed = discord.Embed(title = "Contribution", description = "Contribution to the project is alway welcome, fell free to contribute, edit, clean up, document and improve the source code at: link", color = discord.Color.random())
neko = neko.img("neko")
embed.set_image(url = neko)
await ctx.send(embed = embed)
Rip
random is a command
rename it
what is __path__ supposed to be? https://paste.pythondiscord.com/wejepifafe.sql
There is command named random in that file

Lol
whats the issue?
Do I have to create a __path__ var or smth?
how to i make a command that checks how many people have a certain role then puts it in a embed?
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
U didn't import random
!d clear
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
Is the path a variable or smth
async def MakeATicket(ctx):
try:
channel = await ctx.guild.create_text_channel(f"{ctx.author.display_name}")
await asyncio.sleep(1)
default_role = ctx.guild.default_role()
await channel.set_permissions(default_role, send_messages=False, read_messages=False, view_channel=False)
await channel.set_permissions(ctx.author, send_messages=True, read_messages=True, view_channel=True)
embed = nextcord.Embed()
embed.add_field(name="New ticket made", value=f"<#{ctx.author.id}> has started a new ticket!\nClick the button below to close the ticket.")
await channel.send(embed=embed)
await ctx.reply("Ticket created!")
except Exception as e:
print(e)
'Role' object is not callable
how do i fix this
You are not supposed to call a role object
then how do i get the @ everyone role in that server? i need to set permissions for that channel
The everyone role uses the guild ID as the role ID
also ctx.guild.default_role()
ctx.guild.default_role is an attribute, not a function
So don't put the () on the end
@bot.command(name='embed')
async def displayembed():
embed = discord.Embed(
title='Title',
description='This is a description',
colour=discord.Colour.blue
)
embed.set_footer(text='This is a footer')
embed.set_image(url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
embed.set_thumbnail(
url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
embed.set_author(name='Author Name',
icon_url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown'
'-619.png')
embed.add_field(name='Field Name', value='Field Value', inline=False)
embed.add_field(name='Field Name', value='Field Value', inline=True)
embed.add_field(name='Field Name', value='Field Value', inline=True)
why is my code not working?
add await ctx.send(embed=embed) in the end lol
are u sending the embed?
im making a command for the bot to send embed
Guys im getting:
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
your bot probably doesnt have the appropriate permissions then @full valley
Thats weird
What are you doing exactly?
Your doing something thats returning the error
any command I do returns that
….
@bot.command(name='embed')
async def embed(ctx):
embed = discord.Embed(
title='Title',
description='This is a description',
colour=discord.Colour.blue
)
embed.set_footer(text='This is a footer')
embed.set_image(url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
embed.set_thumbnail(
url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
embed.set_author(name='Author Name',
icon_url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown'
'-619.png')
embed.add_field(name='Field Name', value='Field Value', inline=False)
embed.add_field(name='Field Name', value='Field Value', inline=True)
embed.add_field(name='Field Name', value='Field Value', inline=True)
await ctx.send(embed=embed)
is it possible for discord bots to stream videos in vc channels?
Btw. Saying something doesn’t work doesn’t help anyone, not even yourself. Instead of just saying "it doesn’t work" or "why does this not work" it’s preferable you post code, errors(if any), what you expect your code to do, and overall intentions.
any idea why is it not working?
Why is your commands name embed lol
Refer to what I said literally one message before this one.
oh
i didnt see
it has an error
and what im trying to do is
when i say !embed it sends embed
that’s a warning. not an error. That’s just bad naming conventions.
Your functions name is embed
discord.Color.blue()
I think it doesnt matter its a alias
Your functions name is embed and variable is called embed inside.
uh okay........
Its says colour
You can use color or colour its the same thing
Its suppose to be Color*
Ah i see my bad
Try it its always better i think
Those are aliases
It’s literally not. Danny made them synonymous with each other
Yeah the color kwarg takes both aliases
https://discordpy.readthedocs.io/en/stable/api.html#discord.Colour for more info on that.
wasnt required, but okay ,-,
.
@shut mango
I mean 
Add parenthesis after blue
Noo
Yeah i think its needed
thank you
There
it worked
LOL
Cool
,-, me who was the first one to write this and got completely ignored
oh
its okay xD, dont be
Hmm
help??```py
if msg.channel.id == 869639643167223230 and 888117654931734344:
await msg.delete()
Anyone can look out my project here for getting some idea...
https://github.com/SouvikGhosh05/Discord-Chatbot
wdym?
that's maybe where the message was sent?
improper logic
use or you can check if the id is in a list.
Lojeck 
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
@bot.command(name="8ball")
async def eightball(ctx, *, question=None):
embed = discord.Embed(title=f"8ball", timestamp=datetime.datetime.utcnow())
if question is None:
return await ctx.reply("Include a message")
responses = ['Yes', 'No', 'YES YES YES', 'Probably', 'nah']
res = random.choice(responses)
await ctx.reply(res)
embed.add_field(name="Question", value='', inline=False)
embed.add_field(name='Answer', value=res, inline=False)
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
im trying to make 8ball command in embed but it doesnt work
the only errors
its this code causing the issue embed.add_field(name="Question", value='', inline=False)
it needs to have a value
You could give an empty Unicode for the value of the field
the value cant be ""
\u200b should work iirc
Is there anyway of accessing a function within a cog file in my main file?
Uhhhhhh u should be able to import the cog class but I don't think anyone does that, since, uhhh, that can cause errors
sure
I need help , i want a command that i can do example !blacklist ‘id’ and the person wont be able to use the bot anymore , how can that be possible?
save the id somewhere
then check if the authors id is in that "somewhere" using a global check
sure
Dm?
I have no idea how to make the commands that the problem
dm's?
I have alot of doubts so
ask away ig
okie
Traceback (most recent call last):
File "main.py", line 3, in <module>
from pretty_help import DefaultMenu, PrettyHelp
ModuleNotFoundError: No module named 'pretty_help'
here
this is the error
download the lib
can't use something without obtaining it first
Traceback (most recent call last): File "main.py", line 20, in <module> run() File "main.py", line 17, in run bot.run(token) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run return future.result() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner await self.start(*args, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start await self.login(*args, bot=bot) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'
new issue
kayle
`import discord
from discord.ext import commands
from pretty_help import DefaultMenu, PrettyHelp
from asyncio import sleep
import os
import random
bot = commands.Bot(command_prefix="fe!")
token = os.environ.get("token")
@bot.event
async def on_ready():
print("I'm in")
def run():
bot.run(token)
if name == "main":
run()`
my code error
try printing token
this is the code
done
- i dont need to help you with nameerrors, its basic python
- how tf is it undefined? show me your code
ok
import os
import discord
from discord.ext import commands
from pretty_help import DefaultMenu, PrettyHelp
from asyncio import sleep
import os
import random
bot = commands.Bot(command_prefix="fe!")
@bot.event
async def on_ready():
print("I'm in")
def run():
bot.run(token)
if name == "main":
run()
my_secret = os.environ['token']
it worked
it printed? or what
Thank you!
How would I get the webhook url using the name>?
name?
Yes the name of the webhook
!d discord.TextChannel.webhooks
await webhooks()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gets the list of webhooks from this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Or the webhook in the channel where the command is used
Use utils.find or utils.get
and how would I use that
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
discord.utils.get(webhooks, name=name)
can anyone help
im trying to make a mute command and it keeps on saying "unindent does not match any outer indentation level"
ive tried to make it all correct but it still highlights the end of a bracket and says that
.
Yea
Hi all, i've been working on a simple template for a discord bot and would like feedback if thats appropriate. The bot works (Again, super simple - just connects and displays presence). The purpose is to be a template to use to build other bots, and im looking for overall feedback regarding the instructions, readability, and ofcourse correctness 🙂 if anyone wants to check it out to provide me any criticism, it can be found here - https://github.com/Chasewb91/slatebot
I'm trying to implement this into my discord bot to give a shortened url to my users, but not sure how to do that.
--header 'Authorization: Bearer YOURAPIKEY' \
--header 'Content-Type: application/json' \
--data-raw '{
"url": "https:\/\/google.com",
"custom": "google",
"password": "mypass",
"expiry": "2020-11-11 12:00:00",
"type": "splash",
"geotarget": [
{
"location": "Canada",
"link": "https:\/\/google.ca"
},
{
"location": "United States",
"link": "https:\/\/google.us"
}
],
"devicetarget": [
{
"device": "iPhone",
"link": "https:\/\/google.com"
},
{
"device": "Android",
"link": "https:\/\/google.com"
}
],
"parameters": [
{
"name": "aff",
"value": "3"
},
{
"device": "gtm_source",
"link": "api"
}
]
}'```
Don’t change presence in on_ready()
Do it in your Bot constructor.
any ideas on this?
TY! i'll take a look.
can i clone a role
!d copy
Source code: Lib/copy.py
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).
Interface summary:
or uhhh this
import requests
from discord.ext import commands
class Money(commands.Cog):
"""Trabalha com a conversão de dinheiro"""
def __init__(self, bot):
self.bot = bot
@commands.command(name = "money", help="Verifica o preço de um par na binance. Argumentos: moeda, base")
async def binance(ctx, coin, base):
try:
response = requests.get(f"https://api.binance.com/api/v3/ticker/price?symbol={coin.upper()}{base.upper()}")
data = response.json()
price = data.get("price")
if price: # Se ele achar um preço
await ctx.send(f"O valor do par {coin}/{base} é {price}")
else:
await ctx.send(f"O par {coin}/{base} é inválido.")
except Exception as error:
await ctx.send(f"Ups... deu algum erro.")
print(error)
def setup(bot): #configuração do bot
bot.add_cog(Money(bot))```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Money' object has no attribute 'send'
missed self
does anyone know how to solve it?
oh
but, where does it say coin or base? like: self.coin?
srry for my bad english
async def binance(self, *args)
functions in classes always take self as the first parameter
before ctx
self, ctx, coin, base
solved, thank you
u're welcome
I know, but I always end up either forgetting or not even noticing that it is missing xD
Ok so my bot changes files while running and it's hosted on heroku with github linked but whenever I make a change in the code the files which were generated get deleted. How can I prevent this
heroku doesn't allow you that
So what should I do?
don't use heroku?....
So use repl?
no
So?
sad stuff
Im struggling here, how would that be formatted? All documentation i found online shows presence changed in on_ready, im not sure how else to make it happen.
The documentation your finding is trash. Discord will disconnect your bot multiple times during its process's lifetime. Causing on_ready to fire multiple times.
Thank you!
i have a question how to make xp showin in the rank command cuz i dont know but i need to addd for my leveling system
pls
How can you display the name of the rights that are missing?
sameone knows how to make it?
I'm trying to run this (of course with my api key)
headers = {
'Authorization': 'Bearer APIKEY',
'Content-Type': 'application/json',
}
response = requests.get('https://short.snowmanking.com/api/account', headers=headers)
print(response.json())```
but I get this error.
```Traceback (most recent call last):
File "main.py", line 9, in <module>
print(response.json())
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
Why?
error.missing_perms
Is it possible to somehow display them without square brackets?
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
i mean when sameone types +rank it need shows current rank of user and exp what he gots and he needs to get to another level
but i dont know how to make it
so?
@sage otter Thank you again, I believe i have it cleaned up now ```python
import discord #imports discord.py module, allowing use of their API.
import os #for loading discord token from .env file
from discord.ext import commands, tasks
from dotenv import load_dotenv #for loading dsicord token from .env file
load_dotenv()
token=os.getenv('discord_token') #pulls the discord token from a .env file --
For the bot to launch with this set up, you must have a .env file with the following, excluding quotations "discord_token=DiscordBotTokenGoesHere"
intents = discord.Intents.default() #sets default permissions
client = commands.Bot(command_prefix='!')
discord.Game("Scrabble")
@client.command()
async def ping(ctx):
await ctx.channel.send("pong")
client.run(token) ```
pls sameone
actually not quite, but i feel like im getting closer lol.
no
Can you show how it is correct?
for your case you could do like. ', '.join(error.missing_perms)
thanks you
So what am I doing wrong?
This is the curl code that the website provides to interact with their api.
--header 'Authorization: Bearer tnWzwdnpnaRCkOoW
--header 'Content-Type: application/json' \ ```
```curl --location --request GET 'https://short.snowmanking.com/api/account' \
--header 'Authorization: Bearer tnWzwdnpnaRCkOoW' \
--header 'Content-Type: application/json' \```
So I converted it to Requests like this
```import requests
headers = {
'Authorization': 'Bearer tnWzwdnpnaRCkOoW',
'Content-Type': 'application/json',
}
response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers)
response = requests.get('https://short.snowmanking.com/api/account', headers=headers)
print(response.json())```
What am I doing wrong?
i have a question how to make xp showin in the rank command i mean when sameone types +rank it need shows current rank of user and exp what he gots and he needs to get to another level but i dont know how to make it
how do you make a prefix for a server, i have made the command to set it but im not sure at how to make the prefix just for the guild
how to take the content of the author's message in the command?
plsease
in the get_prefix you would check if the guild id is x, and if it is x you return the guilds prefix. where x is an id.
!d discord.Context.message.content
ctx.message.content
what do you have so far?
what did it print?
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
thanks
I get this. Thats why I was wondering if my conversion wasn't right.
File "main.py", line 10, in <module>
print(response.json())
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
ab.close()
f = open('users.json','r+')
f.readline()
if os.stat("users.json").st_size == 0:
f.write("{}")
f.close()
else:
pass
with open('users.json', 'r') as f:
users = json.load(f)
@bot.event
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await add_experience(users, message.author)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await bot.process_commands(message)
async def add_experience(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 0
users[f'{user.id}']['experience'] += 6
print(f"{users[f'{user.id}']['level']}")
async def level_up(users, user, message):
experience = users[f'{user.id}']["experience"]
lvl_start = users[f'{user.id}']["level"]
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f':tada: {user.mention} zdobyłeś poziom {lvl_end}. Gratulacje :tada:')
users[f'{user.id}']["level"] = lvl_end
@bot.command()
async def rank(ctx, member: discord.Member = None):
if member == None:
userlvl = users[f'{ctx.author.id}']['level']
await ctx.send(f'{ctx.author.mention} Masz poziom{userlvl}!')
else:
userlvl2 = users[f'{member.id}']['level']
await ctx.send(f'{member.mention} Ma poziom {userlvl2}!') ``` i got something like that
oh lol, i just replied !json because i saw the error - thats odd
How can you get an invalid license in another language?
or what?
ey @manic wing i sent a my code
copy.copy()
sure that'd work?
Yea it should
so what do i do exactly now lol
what is __path__ supposed to be, I'm trying to make cog loader? Traceback: https://paste.pythondiscord.com/wejepifafe.sql
copy.copy(role) should work
So I had a 503 error was the issue. Now I have a 200 response. But still not sure how to get the data from it? It says it should respond something like
"error": 0,
"data": {
"id": 1,
"email": "sample@domain.com",
"username": "sampleuser",
"avatar": "https:\/\/domain.com\/content\/avatar.png",
"status": "pro",
"expires": "2022-11-15 15:00:00",
"registered": "2020-11-10 18:01:43"
}
}```
but I'm not sure what to do request.?
Is it supposed to be a variable or smth?
did it respond like this?
no. I printed response by itself and it gave a 200 response.
but not sure where to go from there.
response.json to get that sort of format
I tried response.json and it says there isn't anything?
i thought 200 was an okay
It is
Oh wait gives this
<bound method Response.json of <Response [200]>>
not sure what I typed instead of json last time 
try ```py
a = response.json
print(a)
it would be response.json()
and then you can dict index to it like a normal dict
That looks more like it 🙂
{'error': 0, 'data': {'id': 3, 'email': 'email', 'username': 'AnswerBot2', 'avatar': 'https://www.gravatar.com/avatar/6ce01b5db930169803c380739e24e7e8?s=64&d=identicon', 'status': 'free', 'expires': None, 'registered': '2021-12-08 17:38:38'}}
so how would I grab one of those json parts?
!d dict || yeah thats a dict
class dict(**kwarg)``````py
class dict(mapping, **kwarg)``````py
class dict(iterable, **kwarg)```
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
Dictionaries can be created by several means:
• Use a comma-separated list of `key: value` pairs within braces: `{'jack': 4098, 'sjoerd': 4127}` or `{4098: 'jack', 4127: 'sjoerd'}`
• Use a dict comprehension: `{}`, `{x: x ** 2 for x in range(10)}`
• Use the type constructor: `dict()`, `dict([('foo', 100), ('bar', 200)])`, `dict(foo=100, bar=200)`
data = response.json() and index to it like data['error']
need help
@commands.command()
async def moveall(self, ctx):
mainVC = ctx.author.voice.channel
for channel in ctx.guild.channels:
if isinstance(channel, discord.VoiceChannel):
for member in channel:
#print(f"Moved {member.name} to {mainVC}")
await member.move_to(mainVC)```
it just doesnt move anyone
How can you get an invalid license in another language?
😳
ab.close()
f = open('users.json','r+')
f.readline()
if os.stat("users.json").st_size == 0:
f.write("{}")
f.close()
else:
pass
with open('users.json', 'r') as f:
users = json.load(f)
@bot.event
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await add_experience(users, message.author)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await bot.process_commands(message)
async def add_experience(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 0
users[f'{user.id}']['experience'] += 6
print(f"{users[f'{user.id}']['level']}")
async def level_up(users, user, message):
experience = users[f'{user.id}']["experience"]
lvl_start = users[f'{user.id}']["level"]
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f':tada: {user.mention} zdobyłeś poziom {lvl_end}. Gratulacje :tada:')
users[f'{user.id}']["level"] = lvl_end
@bot.command()
async def rank(ctx, member: discord.Member = None):
if member == None:
userlvl = users[f'{ctx.author.id}']['level']
await ctx.send(f'{ctx.author.mention} Masz poziom{userlvl}!')
else:
userlvl2 = users[f'{member.id}']['level']
await ctx.send(f'{member.mention} Ma poziom {userlvl2}!') ``` i did this so far @manic wing sorry for ping
x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
prefix = x.fetchone()
prefix = str(prefix)
await msg.channel.send(f"My prefix for this server is n! and {prefix}")```
sends My prefix for this server is n! and ('{prefix}',)
any one can help me ?
Error??
Depends
2secs
none it just puts ('',) round the prefix which for me is set with !
My prefix for this server is n! and ('!',)
x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
prefix = x.fetchone()
prefix = str(prefix)
await msg.channel.send(f"My prefix for this server is n! and {prefix}")
``` Try that
me ?
alright ty
Where is VoiceState??
nope still ('!',)
i dont know ^^'
you have 2 prefixs defined change one to like prefix2 or something.
alright
I don't know I don't mess with voice chats, uhm... Yeah, sorry I tried.
{prefix[0]} sorted it 😄
Okay. I tried.
yeah thank you very much sir
Np.
i am confused
okayy no probl
I have this command where it randomly chooses a time from a list and then sleeps until it finishes but it's not working, any idea why?
I have 1,2,3,4 and 5 as seconds in the list
But it doesn't work
But when l choose a different list with 5 seconds it works
For some reason this still adds the role id to the json file even if it is not valid?
@commands.command()
@has_permissions(administrator=True)
async def addstaff(self,ctx, role_id=None):
try:
role_id = int(role_id)
role = ctx.guild.get_role(role_id)
with open("config.json") as f:
data = json.load(f)
data["staff-roles"].append(role_id)
with open('config.json', 'w') as f:
json.dump(data, f)
success_embed = discord.Embed(title="Staff Role Added", description="You have successfully added `{}` to the list of roles that can run moderation commands!".format(role.name), color=0xD22C45)
await ctx.send(embed=success_embed)
except:
error_embed = discord.Embed(title="Role Error", description="That isn't a valid role ID. Please try again with a valid role ID.", color=0xD22C45)
await ctx.send(embed=error_embed)
I wanted by bot to send a message whenever a certain profile post something on Instagram, I thought webhooks would be the way to go but now I’m not so sure
hmm. Now I'm getting an error saying I'm not passing the shortened url? This is the full code now.
import requests
from urllib3.exceptions import InsecureRequestWarning
# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
headers = {
'Authorization': 'Bearer njcrFyvTspYpWfmU',
'Content-Type': 'application/json',
}
response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers, verify=False)
data = '{\n "url": "https:\\/\\/google.com",\n "custom": "google",\n "password": "mypass",\n "expiry": "2020-11-11 12:00:00",\n "type": "splash",\n}'
response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers, data=data, verify=False)
data = response.json()
print(data)```
Here is the error
```py
{'error': 1, 'message': 'Missing required parameter: url'}```
Isn't the URL being passed? Under Data?
Slash commands take 1 hr to load
Are you fr?
how do you check if there is more after a mention
if self.bot.user.mentioned_in(msg):```
That's bulls*****it
any ideas?
If get_user() returns None that means that user isn’t on cache
Alternatively use fetch_user()
You should always close the cursor(s) after you used the data
newone = '111 - 222'
newone = my_string.partition("- ")[2]
Output : 222
How do I get the output to be 111?
Yes.
Cursor is basically the connection, yeah if it not used for half an hour close it but else it's best to let it stay open.
No
Cursor is not the same as a connection.
When you are done using the cursor, close it. Simple rule.
If you don't agree, search it up and everyone else does agree.
Your right mb, i don't use cursors anyways lol
Ye
Anyone?
how do you check if there is more after a mention
if self.bot.user.mentioned_in(msg):```
!d discord.Message.mentions ?
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
no because one of my prefixes is the mention, but when you mention and use a command it still comes up with the message + the command
Hey everyone, does anyone know a good place to learn the python discord library? I'm kinda stuck with just the official documentation.
I've made a few examples. However, it's using a fork called disnake. You can check it out. https://github.com/ScopesCodez/disnake-examples
Examples you can use whether in disnake.py (https://pypi.org/project/disnake/) or discord.py (https://pypi.org/project/discord.py/) - GitHub - ScopesCodez/disnake-examples: Examples you can use whe...
The GitHub examples are an excellent place to learn
I also had some fun looking at RoboDanny’s source code (discord bot made by the creator of discord.py)
Thanks a lot for the advice, guys < 3
how do you do redirect_uri in OAuth
There are better ones imo
The disnake repository has ones that are good too
I didn't say mine are the best. 
and there is a WIP guide
You can make it better though
Like type hintings, docstrings etc etc
I am trying to make a command that changes the prefix of the bot but I am really struggling. How do I replace something in json, this is what I have so far.
@commands.command()
async def prefix(self,ctx,prefix):
with open('config.json') as f:
data = json.load(f)
valid_user = False
for role_id in data["staff-roles"]:
try:
if ctx.guild.get_role(role_id) in ctx.author.roles:
valid_user = True
except:
pass
if valid_user or ctx.author.guild_permissions.administrator:
with open('config.json') as f:
data = json.load(f)
```json file:
```json
{"staff-roles": [], "prefix": ".", "verified-roles": []}
Do you want to also rewrite the JSON file?
!e
JSONs in Python are parsed into a 'dictionary'
With those you can change key/value pairs, so say we have the dictionary:
my_dict = {"staff-roles": [], "prefix": ".", "verified-roles": []}
# to change prefix to ','
my_dict["prefix"] = ","
print(my_dict)
@brave vessel :white_check_mark: Your eval job has completed with return code 0.
{'staff-roles': [], 'prefix': ',', 'verified-roles': []}
Then, you can just rewrite the file
def get_prefix(bot,message):
try:
db = sqlite3.connect("Config.db")
cursor = db.cursor()
x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
a = x.fetchone()
if a == None:
return
commands.when_mentioned_or("n!")(bot,message)
else:
return commands.when_mentioned_or(a[0],"n!")(bot,message)```
when you @ the bot and use a command it sends the command twice
I think that's not a problem with the code itself, you might be running two instances of your program at once, so it sends twice
Well first things first, don't always connect to the database.
As for every message you make a new connection and new query, which is pretty bad.
im not
ah would that fix the double command though
Don't think so, but at least latency and other issues you will face in the future.
You might think you're not, but that's happened to me before too. I think usually it's solved with just completely shutting down the program with whatever you're running it on and then restarting it
yeah ig
just done that
ah
its quite weird
hey! i need to check if user has role... How can i do it?
What would be the context of checking if the user has a role? Would it just be making sure that only people with the role are running the command or something else?
just check like this: if user.has_role(role): pass
If it's the latter, something like:
role = discord.utils.get(ctx.guild.roles, name="Role name goes here")
# if you know the member you want to check the role from
if role in member.roles:
# code goes here
ty dude
np :D
@brave vessel do you have a idea on why it comeds back 2 times?
Why not use it's id?
Not sure honestly, my earlier guess would be my only one
for getting the role?
Yeah?
Ah, you could do that, I'm mostly used to the name kwarg though
it'll probably save some time though
I mean using guild.get_role
an error appears
That's because member needs to be defined as the user you want to check has the roles
you could just replace member with user if you already defined uesr
but i don't wanna it
i want to the member type !config and then the bot gives a role
wdym?
So ctx.author?
Ah, I mean you could, but would that work cross-server? Like I know quite a few bots auto-create a Muted role I think and check for that role via a name because the ID won't be consistent cross-server
This is a genuine question btw, not sure
oh does guild.get_role support the name of the role?
guessing not actually
yes but the dpy dont recognizes ctx.author as a discord.member
If it is done in a server, why won't it?
^ it will
sends 2x
ohh, the colors of the embed are different, are you running something twice internally?
Oh I thought he wanted to do only from one server
My bad
Oh wait maybe, then an ID will be better, just decided to use the name kwarg because it's a safer bet
uhhh hold on
no worries! your suggestion is better than mine with one server only
@brave vessel no i forgot its random
ah
this is a different command
Try to shut down your bot and re-run
have done, ill swap token rq
The best way I use is to reset the token
its still happening
yeah very
Maybe you are running it from multiple instances by accident?
nope
tried that
its really annoiyng
Show code
okay here
def get_prefix(bot,message):
# try:
db = sqlite3.connect("Config.db")
cursor = db.cursor()
x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
a = x.fetchone()
a = a[0]
return commands.when_mentioned_or(a,"n!")(bot,message)
# except Exception as E:
# print(E)
client=commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=discord.Intents.all(),help_command=None)```
Your command was prefix
wym
What’s get_prefix
the function
Is it an alias?
I doubt the problem is with the command itself
Alr
the top bit
def get_prefix(bot,message):
# try:
db = sqlite3.connect("Config.db")
cursor = db.cursor()
x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
a = x.fetchone()
a = a[0]
return commands.when_mentioned_or(a,"n!")(bot,message)
You both talk about different things, @slate swan he wanted you to send the prefix command
yes
wdym the get_prefix part?
OHH
No, the command itself
Your function was get_prefix
bet but it happens on all commands
The command was prefix
Yeah that's why I doubted it was with the command itself
Is it in every single command?
yeah
yep 99% let me check
yes every cmd
how?
ah
Try to use a print statement in the command
Wait nvm it doesn't matter really
Oh wait
You are using cogs right?
yeah
yeah and process
ye
Inside the cog?
subprocess?
Not good, listeners don't need it
not that cog but in a cog
😭
uh
Cog.listener is a listener, you shouldn't use process_commands in it
Why are the colors different
@commands.Cog.listener()
async def on_message(self,msg):
if msg.author == self.bot:
return
if self.bot.user.mentioned_in(msg):
try:
x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
prefix = x.fetchone()
embed=discord.Embed(title="", description=f"My prefix for this server is `n!` and `{prefix[0]}`", color=discord.Color.blurple())
# await msg.channel.send(embed=embed)
except AttributeError:
embed=discord.Embed(title="", description=f"My prefix is `n!`", color=discord.Color.blurple())
await msg.channel.send(embed=embed)
await self.bot.process_commands(msg)
return```
Just wondering
random
See, delete the line b4 return
You only need it in on_message event
Not listener
Delete await self.bot.process_commands(msg)
okay
And than retry
omg it works tysm
Np
tysm ily
The moment where this channel goes quiet
Lol
How can I get started on python? i want to learn python to program my bot in discord Discord.py
NOTE: I'm Brazilian but I understand English
i started with youtube tutorials tbh
There are some Google resources (my attempt to make this sound as nice as possible)
I don’t do discord nowadays
!resources will help you understand Python basics and everything you need for discord.py. Than I would suggest looking at discord.py documentation, GitHub code examples, and this tutorial: https://vcokltfre.dev
NOTE: discord.py is an advanced lib, envolving advanced Python and complicated codes, you SHOULD learn basic and more then mediocre Python to start discord.py.
Good luck!
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I’m trying to upload something to GitHub
There is a y…never mind
OK thank you scythe,Download,Nir
Looks like I'm going to suffer a little lol
i want to check if the user has a role. if it has this role the bot should not say anything, but if it does not, the bot will speak a text... how can i do this?
Why do people call me download
Your nick is Download 
I'll change my name
How to check if a message pinged my bot?
So I am just wondering, how can I create an event in discord.py where if a user pings the bot it will respond with a message?
I have not found anything concrete anywhere on how to do this and I w...
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
message.mentions()
how would i use it with ctx?
ctx.message.mentions()
If ping in message.mentions
oh my bad
i think i was getting it confused with the member.mentioned_in()
so, what would ping be? @quaint epoch
a member object
okay
discord.Member
Look in the docs
kay
@quaint epoch
@bot.command()
async def _play(ctx):
if not ctx.author.voice:
return await ctx.send("You are not commected")
Why this dont work for lavalink
You already have a command named play somewhere
Try to rename it
Yes but its lavalink it dont send messagge u are not in voice channel
Šta?
Balkan?
Da
Lol
Ma brate lavalink je bot ne senda message kad kucas $p i kad nisi u voice
Ne pise kao
You arw not connected in voice
Valjd vidis code sto sam poslao 😂
Tu piše
Command play alr exist etc.
Pa znam da to pise ali kako mogu nap
Da
Isti ko prej?
Da
Pa bukv isto
Od kode
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
@pale turtle
Do you know what the error is telling u
?
like create_instant_invite = True
Oh, I think It’ s named same as in discord
Np
I need the python code for command where are two arguments, first arg1 is to choose one option from the list, second arg2 is to put value by the user (from the screen opcje = options; obliczanie = calculation; mnożnik = multiplier; wartość = value). Than bot will calculate (arg1 * arg2) and return result for the user. I can PAY if someone learn me how to code this.
I need the python code for command where are two arguments, first arg1 is to choose one option from the list, second arg2 is to put value by the user. Than bot will calculate (arg1 * arg2) and return result for the user. I can PAY if someone learn me how to code this. I can sand a photo of this in private chat.
What do you mean by "value by the user"?
Not sure if slash commands let you enter in text
Never mind it has a STRING type
Is it possible to create a loop that checks for whether or not a message is actually sent and retry until it is?
if the message isn't sent you'll get an error
It doesn't seem to be an error which is picked up by Python though
sending a message can raise one of 3 exceptions:
if you don't get any of these, then the message is sent
If you don't get an error and the message isn't sent, you have a faulty error handler.
So the error resulting (presumably from connection issue) is as such:
Task exception was never retrieved
Functionally, each server has a task object which then replaces itself with the next task barrel of monkeys style, the problem is, when a connection issue arises it effectively loses the chain and doesn't have an error and instead simply stops trying to continue
Can you send the full traceback?
I want to delete the info of the server in the .json via the command...
Task exception was never retrieved
future: <Task finished name='Task-5818' coro=<BarBot.take_turn() done, defined at /app/cogs/barbot.py:167> exception=DiscordServerError('503 Service Temporarily Unavailable (error code: 0): <html>\r\n<head><title>503 Service Temporarily Unavailable</title></head>\r\n<body bgcolor="white">\r\n<center><h1>503 Service Temporarily Unavailable</h1></center>\r\n<hr><center>cloudflare-nginx</center>\r\n</body>\r\n</html>\r\n')>
Traceback (most recent call last):
File "/app/cogs/barbot.py", line 171, in take_turn
await self.pass_the_mic(server)
File "/app/cogs/barbot.py", line 179, in pass_the_mic
await server.approved_channel.send(f':microphone2: **Pass the Mic!**')
File "/usr/local/lib/python3.9/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/usr/local/lib/python3.9/site-packages/discord/http.py", line 252, in request
raise DiscordServerError(r, data)
discord.errors.DiscordServerError: 503 Service Temporarily Unavailable (error code: 0): <html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>cloudflare-nginx</center>
</body>
</html>
Returned error there is 503 Service Temporarily Unavailable, is this something you can target with try except?
Ah that sounds like a server issue
This has nothing to do with your bot, just a discord end error
Nothing you can do to fix until discord fixes their issue
Perhaps implement an exponential backoff algorithm
- try to send message
- if it doesn't work, wait 2 seconds
- try to send message
- if it doesn't work, wait 4 seconds
- try to send message
- if it doesn't work, wait 8 seconds
- try to send message
- if it doesn't work, wait 16 seconds
- try to send message
- if it doesn't work, wait 32 seconds
so on and so forth
Interesting, so how would I go about actually implementing that?
Given that the tasks are effectively an attr on an Object, how do I handle that spawning/retry?
Have a class that has the last wait time stored in memory, each time you call a certain method, double it, and return it while you also store the new doubled number in memory
I've seen this actually implemented in the discord.py library's source code itself
I really wish I could tell you but frankly it was a while ago and I don't exactly remember
An never mind here it is:
https://github.com/Rapptz/discord.py/blob/master/discord/backoff.py
Its done inside of run
I actually thought it was hidden away as a class in some arbitrary file but nope, here we are haha
Ooh, interesting! I see this is in the official Discord.py git, does that mean it is something accessible from the Discord.py package?
No it's mostly used within the internals
I doubt it was meant for use, but with some tweaking you could probably get it to work
though i'd have to suggest you replicate the class yourself, simplify it down perhaps, and use that instead
Is there any way to invoke it? It doesn't seem that however it is internally implemented that it is working in our case
I mean it's just a class so perhaps you could just import it and call its methods
But yet again it wasn't designed for front end use, so who knows what it might break
It has a lot of elements to it that aren't really needed for regular use (very in-depth type hinting, more functionality than you would need for a simple backoff algo)
you could strip it down to a very simple class that works efficiently
I think the first thing I will try is just a linear retry loop in a very simplified command set, just a simple loop that does try except and if there is ever a service unavailable it passes the command into it and also passes the wait time into the method as args
Sound alright
what is the actual exception in Dpy?
What do you mean
the Exception
For sending a message?
Construct the class, E.g ExponentialBackoff, next when you want to retry do ExponentialBackoff.delay() to get the time, then sleep that amount
Oh 503 is a HTTPException or something of that sort
No
Well, yes ig
But its a server error
Something went wrong with discord's servers and their offline
Right it should raise a discord.HTTPException though?
ooh okay, let me look in the docs at HTTPException and see if there is a special case handled for that
pretty sure the error has .status attribute
The first one add a channel , i want the second too remoove the channel.
help please
you can just check if the .status == 503 or something of that sort to check for an outage, if so start the exponential/linear backoff algorithm
You probably want the code attribute of the error
That's the discord specific error code, althought it might be the status
https://discord.com/developers/docs/dispatch/error-codes#error-codes
list of codes and what they mean
I will do some testing and see what I can make happen 🙂
. help please lol
awesome, best of luck
Thank you so much! ❤️
And for an outage check you can just check if the error code starts with 5
Cause anything from discord that is a 5xx error is a server error
anybody no?
json.dump() will only dumb the dict contents to the json file, just remove the channel from the dict and dump that
What is the structure of your JSON file?
guild id
channel id
invite
Are they seperated into nested dicts?
I see
It would probably be a better idea to use the guild ID as the key to the nested dict
would be easier to remove
with your current structure it's going to get really messy and unconventional to remove a certain guild
using an actual database would make this much easier
Awesome, put something like postgres or MySQL on it
no idea how to set it up tho
as oppose to a .json?
right, except it's a full fledged database
.json on the other hand, is only a file format
it's terrible at storing persistent data
due to sqlite's speed and lightweight-ness, many people even use it as a caching layer for their real databases
okok i see letm e download really fast
Ehhh I wouldn't really recommend sqlite as a cache for your database
If you want a good cache you'd want to use redis
Caching stuff is usually for scalability and redis just crushes that
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'check' is not defined?
Agreed, redis is awesome for caching
Define check
@sick birch
...def?
def?
the file extension
i don't have that
correct me if i'm wrong here but sqlite will auto generate the file if you try to connect to a file that doesn't exist
not sure if you should make a .db file by hand as sqlite might fill it up with some sort of formatting data
there are plenty out there, a quick search for sqlite database browser will reveal many
or you can just print it out using python to the terminal
Once you get sqlite setup you want to make sure you are using an async driver, since discord.py is an asynchronous environment
^ like asqlite or aiosqlite
asqlite was actually made by Danny (creator of discord.py), it has better defaults and is lightweight so i would suggest that
how can I find a role ID from the role name
discord.utils.get(...).id
do I put the role name in the parenthesis?
sure just ask

