#discord-bots
1 messages · Page 984 of 1
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.
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 23, in <module>
client.load_extension(f"commands.{filename[:-3]}")
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.Prefix' raised an error: SyntaxError: invalid syntax (functions.py, line 68)
there is something wrong in ur Prefix.py
ig
Traceback (most recent call last):
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Trent/commands/Prefix.py", line 6, in <module>
import functions
File "/home/runner/Trent/venv/lib/python3.8/site-packages/functions.py", line 68
nodes = tuple(map(lambda (k, v): process_node(inner, k, v),
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 23, in <module>
client.load_extension(f"commands.{filename[:-3]}")
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/runner/Trent/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.Prefix' raised an error: SyntaxError: invalid syntax (functions.py, line 68)
the thing is i have no file called functions
or am i dumb?
@slate swan
u can put () which defning params for lambda
btw, can you do ```py
@bot.command()
async def foo(ctx):
pass
@foo.on_error()
async def on_error(error):
print('error')```
what
it should be lambda k,v: ... instead of lambda (k,v): ...
(lambda arg1, arg2: print(arg1, arg2))('hello', 'world')
ofc you can just set a lambda to a variable and pass the args on that
oh yea, didnt even see that lol
dude i dont even know where i typed it, functions.py isnt a file
from prefix?
oke wait
need to be in commands cuz of the help cmd
its same as cogs just other file
message to long wait
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
wait
ya ok
show ur imports
nah thats just discord's shitty way to flagging links, if a link ends with .py it does that
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what is functions???
How do i use discord.Client.wait_for for multiple events? Specifically message and reaction_add
what module is it, what does it do, why did u start using it at the first place??
imma delete all and start new ig
bru
done, pending = await asyncio.wait([
bot.loop.create_task(bot.wait_for('message')),
bot.loop.create_task(bot.wait_for('reaction_add'))
], return_when=asyncio.FIRST_COMPLETED)
try:
stuff = done.pop().result()
except ...:
# If the first finished task died for any reason,
# the exception will be replayed here.
for future in done:
# If any exception happened in any other done tasks
# we don't care about the exception, but don't want the noise of
# non-retrieved exceptions
future.exception()
for future in pending:
future.cancel() # we don't need these anymore
Well they have to work together
what do u want to add buttons to?
u will obv have to make the 3 buttons and send it with the embed
Hello, I am trying to set up a random gif generator from Tenor using the API Key.
I can get it to generate the 1st gif in the query, but not a random one... Can anyone help? Here is my code and a photo (sowing every call of the command generates a new number but how I can get that to pick a new gif, I don't know 😢 )
@commands.command()
@commands.has_guild_permissions(send_messages=True, embed_links=True)
async def gif(self, ctx, query):
async with aiohttp.ClientSession() as session:
TENOR_API_TOKEN = 'XXXXXXXXXXXXX'
embed = discord.Embed(colour=discord.Colour.dark_red())
response = await session.get(f'https://api.tenor.com/v1/search?q={query}&key={TENOR_API_TOKEN}&limit=30&media_filter=basic')
data = json.loads(await response.text())
gif_choice = random.randint(0, 29)
for result in data['results']:
for media in result['media']:
print(gif_choice)
embed.set_image(url=data['media'][gif_choice]['url'])
await session.close()
await ctx.send(embed=embed)
However, if I change embed.set_image(url=data['media'][gif_choice]['url']) to embed.set_image(url=media['gif']['url']) it shows the first gif from the query as shown in this photo... It doesn't randomise from the top 30 on that search 😢
??
go and take a look
then u will understand what i mean
I don't understand how that helps my issue? 😕 😄
im not answering ur question 
just telling im killing pepo in #help-pear
and idk how to fix ur problem either
gif_choice is takes a random number from 0 to 29
And btw thats a loop for result in data["..."]
the code is over-complicated than it should be
Not really i just dont know how to use the api
I mean, api usage "might" be correct, but, the code seems over-complicated ngl
I am still learning, may be over complicated, but it works 😄
I think it should be something like py array = [r for r in data["results"]["media"] data = json.load(await response.text()) embed.set_image(url=random.choice(array))
note : idk though, i've never used the api so ye
Yep
Ok, let me try this 🙂
Eh im not sure 😭
Btw do ["results"] and ["media"] return a list?
at least dont cry 😔
😔 im at school rn and i have exam in the next hour (i didnt know that i have an exam but ye)
How can my bot check if someone else than the author reacted to the message and then send a message, that only the guy read? Like Dank Memer or is it not possible?
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
It doesn't seem to no
Can u print(data["results"])
install the module
!dotevn
Using .env files in Python
.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.
Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.
In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:
TOKEN=a00418c85bff087b49f23923efe40aa5
Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:
from dotenv import load_dotenv()
load_dotenv(".env")
The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:
from os import getenv
my_token = getenv("TOKEN")
For further reading about tokens and secrets, please read this explanation.
you can only send ephemeral messages through views (buttons/slash commands, etc.)
Yes, it lists 30 urls
Can i see the urls (output)?
Hey @onyx apex!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
On pypi it is python-dotenv
and how would that work with slash commands?
@onyx apex since that returns a list of urls then make a random.choice to get "random url" from the list
which library are you using?
random.choice(data["results"]["url"]) something like this
I think its python-dotenv
did you install dpy 2 already?
nah
oh no
:<<
i just slept when i was making giveaway cmd
Maybe eh restart ur ide?
idrk
pip install python-dotenv
from dotenv import load_dotenv
import os
load_dotenv()
_s = os.environ.get("key")
This just comes up with syntax error, I can't see why though... embed.set_image(url=random.choice(data["results"]["url"]))
well, you need dpy 2 master branch installed to use its slash cmds which are horrible
!e py import random d = {"d" : {"url": "7", "url" : "3"}} print(random.choice(d["d"]["url"]))
Oh
@slate swan :white_check_mark: Your eval job has completed with return code 0.
3
Mmm
Yeah, I have random imported too, I'm confused 😄
No problem, thanks for trying to help 🙂
hola :D
await channel.send("uwu")
do it after all your imports
from dotenv import load_dotenv
import os
import discord
import config
load_dotenv()
token = os.environ.get("BOT_TOKEN")
bot.run(token)
not defined
if any((channel for channel in ctx.guild.text_channels if channel.mention == msg.content)):
oh you're using this huh
..
well, you cant really send messages anyways like that
then ill use this only
bad
huh
wow which theme
maybe fit that into a list comprehension?
[await channel.send("exists") for channel in ctx.guild.text_channels if channel.mention == msg.content else await channel.send("doesnt exist")]
hm, the dotenv module still doesnt work, weird
... i not only need to send
run: python -m pip install python-dotenv in the terminal, then restart your ide
well
then you gotta use a for loop
which is bad (according to where you're using it)
..
then instead of waitfor i need to use like this !g st #bot-commands 1 giveaway title
;-;
sheesh, do you have multiple versions of python installed?
why cant i import Button and ButtonStyle?
ew, what library is that
well, then you know what to do
seemed like a 3rd party lib
they're the same?
idk, maybe?
uh
<@&831776746206265384> (sorry for the ping, somebody posted an inappropriate video which they deleted)
noice
attacking
idk some kind of missile target
at begn
probably a terrorism supporting one
ye
pip install ig
change your python version in vs code from the bottom left corner. Period.
..
a big hand of applause for sparky
they got multiple python versions installed
and I'm getting ignored for that
I think I will just go away from here now
Do. You. Have. Multiple. Python. Versions. Installed. ?.
..
wha-
then check huh 😭
is there any input method in discord ui
Modals (or normal text inputs)
modals ok
if x.type == string:
from discord import ui
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
do i write it like this?
ok
its best ever for what im doing!!!
wow!
congrats
aval in disnake?
🥳
why do I always get ignored 😔
:/
:D
alt f4
jkjk
||I told them to restart twice before so idk if that really is the issue||
3 time alt+f4 then enter key
gg
funny
im going to sleep byebyeeee
good nighto, have a good sleep!
thanks thanks
whats the time now in ur place
3:31 pm
its 1030pm here so im sleeping
7 hours hmmm
:)
its 8 here
bye
@slate swan how long are you online?
@slate swan uh why?
Cuz they be been here since morning
..
Lol
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
..

lol
In this video I'll be showcasing the best python editors and ides. These software tools help to speed up your coding and come with a ton of useful features. Each python IDE and editor on this list has its pros and cons and different use cases associated with it. Do you agree with my list? Let me know!
⭐️ Thanks to Kite for sponsoring this video...
It might help? 
i think he will show u how to "run file" "download modules" etc (not sure) if u still need help just go to that guy's channel
ok
Wait
What's that syntax highlighting?
Nvm it's JS
msg = await ctx.send()
await msg.edit(embed=None, content="Embeds Removed!")
Bro
Don't do dpy if udk basic Python
just edit the code you extra knowledgeable person true
Cba to edit the code even when I gave the code he literally has to copy paste
Why do u have a try except?
you are not making and sending the embed tho, in the ctx.send
how do i tell if an arg is a number, i tried
@commands.command()
async def _info(self, ctx, *, var):
if not isinstance(var, int):
return await ctx.reply('Not XUID')
await ctx.reply('Is XUID')
and it doesnt work
it still gives an index out of range error
var will always be a string
You need to type hint it to an int
the thing is i dont want it to be an int lol, im trying to see if var is a number or not
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
I was about to do that
how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message
how can i find a numeric role in a users roles?
I watched a youtube Tutorial on modals and thats literally the same as in the video
it takes an intents kwarg now
where is Spyder lol
Th?
Thonny, very famous IDE, mostly used in computer science classes I think
what?
you mean how to get role per id ?
(ctx.author).roles
how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message
that gives you a list of the roles
[r.id for r in user_role] creates a list of the role but ID
Huh?
I answered them already
^
That works with interactions
Oh i didnt see
How to check if the user has a role that is a digit like 1, 2, 3 etc but I got it myself now
just grab the roles of the user and check if the role you are looking for is in that list
[role for role in member.roles if role.name.isdigit()]
^
hey so what does the email scope do on my discord bot application?
or you do it directly like that
!d str.isdigit
str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
filter(lambda role: role.name.isdigit(), member.roles)
``` this would be faster
if result[8] >= 50:
print("Value is Greater Than 50")
else:
print("Value is less than 50")
TypeError: 'NoneType' object is not subscriptable
The Object has a value of 51..For whatever reason it says its a None Type...
Does Anyone Know Why?
That works, but i want the code to check if it is above 50...
What does it print?
sultan, the error means that the object you check in is None
51
what does the print say
If result prints 51 why are you indexing it at 8?
There are 9 Rows in the Database
I want it the check the 8th row
SQL
database objects use key search not index search.
how did you get the result
db = sqlite3.connect('data/Test.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM TestTable WHERE user = {user.id}")
result = cursor.fetchone()
@commands.command()
@commands.has_permissions(manage_messages=True)
async def tempmute(self, ctx, member:discord.Member, *, time:TimeConverter = None, reason="Reason unspecified"):
role = discord.utils.get(ctx.guild.roles, name="Muted")
await member.add_roles(role)
await ctx.message.delete()
embed = discord.Embed(
title=f"Tempmute: {member}", description=f"Reason: {reason}\nDuration: {time}\nBy: {ctx.author.mention}")
await ctx.send(embed=embed)
if time:
await asyncio.sleep(time)
await member.remove_roles(role)``` Can someone tell me why my tempmute is broken? It doesn't unmute after specified time
don't do str formating in sqlite
Did the bot got restarted in that period?
!tags
no
!sql-fstring
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
It works fine for everything else apart from that one command.
have a look here
no, because it can leads to big error and completely ruin your data base
@slate swan I've installed Discord.PY2 but all my code is wrong now because its still in version 1.7.3. How could i rewrite it the fastest way?
i see
Does it also not work when time is set tot like 10 sec?
that's what I did for the test
use find and replace?
Is time an int? maybe conversion is going wrong.
but now i will have to rewrite all my slash commands right?
probably
If you use an extension for 1.7.3 yes.
well if result is 51 you can't use an index, especially with fetch_one
Alr i made the changes.
You can't index database objects.
fetch_all returns a tuple, you can get the index from that it works just fine
Since those are a list of objects and fetch one fetches the object.
anyway, if the result 51 there is nothing to iterate through
He want's to index a row.
@compact ruin in your data base, did you use int or str for the user id ?
Int
wrong message but yh int
Doesn't explain the None type subscription otherwise it would say int. My guess is that that user isn't in the database.
User is in the database. It prints the name and everything fine. Also prints the 51 for the user
then why do you want to get the index
Could you show that?
Yes that's what I'm trying to explain to you lol
lmao
I didn't get that haha
That's why I said this #discord-bots message
yeah Sultan, you're selecting all the rows with * and then just one with fetch_one
im trying to get the 8th row
No fetch all returns all rows, when searching on id you should only get one.
I just want the one not all
result["row_name"]
look here panda
"SELECT *
Tried that already lol
result = cursor.fetchall()
Does not work
cursor.execute(f"SELECT colmn FROM TestTable WHERE user = ?;", (user.id,))
yeah I told them about that already
hold up..
right there lol
would a Cog listener be a problem?
I changed the *
Cause for commands its working fine
depends
are you in a cog and is this a command
that's why I asked you to show the entire code
this is a listener.
Commands work fine

hello guys
i need some help
so you know how you can do like .get picture (picture used as an example, the bot would reply to this message by sending a photo)
idrk if we can pull it off in python cuz i learned it from js^
@commands.Cog.listener()
async def on_message(self,message):
db = sqlite3.connect('data/Test.sqlite')
cursor = db.cursor()
cursor.execute("SELECT * FROM TestTable WHERE member_id = ?", (user.id,))
result = cursor.fetchone()
await asyncio.sleep(0.5)
if result[8] >= 50:
print ("Value is Greater than 50)
else:
print ("Value is less than 50)
ok so ive got a verify command im working on, where the bot will send a code and the user has to repeat it, but i wanna make it so the user only has a specific amount of time to repeat the code, how would i do this?
@bot.command()
async def verify(ctx):
code = ("N6hT91")
await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")
def check(m):
return m.content == f"{code}" and m.channel == ctx.channel
await bot.wait_for("message", check=check)
await ctx.send("test successful")
do you want to select all columns or just one
Add a timeout
Just the 8th Row
add timeout in wait_for
that doesnt help me, i asked "how to add timeout" and your reply is "do it"
row or column
but yh one row
how?
Oh sorry my bad lol
can u send me link to some example?
by looking at the function and see that timeout is an argument
Column not row lol
yeah
so as panda said earlier you don't want to SELECT *
just the column you desire
right there
to select the 8th column just put the column name instead of colmn
still says none type
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@opal cosmos
what did you type
SELECT Field8 FROM TestTable etc
can i use .send() ?
show me the name of the columns
yeah sry i forgot to tell u i got it figured out
Hold up lemme try something rq
and did you remove the [8] from your result
yh
SELECT COLUMN1, COLUMN3, COULUMN4 FROM table_name
is how you select columns
then the element you're looking for isn't in your databse
that's what they did
I just saw the select * message and wrote it
hi
sup'
Nvm fixed it, Works now.
nice
One more question is there a way to get the reply to a message someone gives?
also ty for the help you lot
Hello I’m making a bot that allows you to send message to a channel to echo your message via dms
But I wanna make it so if someone sends discord link it blocks them
istg APIs suck
well
if message start with
Author.block()
don't remember the syntax but something like that
Your bot cannot block someone
ahem ahem
especially proxying ahem ahem
@bot.event()
async def on_message():
If message.content(“hi”):
await ctx.send(“hi”)
Sad
proxy servers uwu
Wait what is this
I love proxy servers and the fact that you can edit data using them
No, it is a pain to try proxy requests from one port to another 😔
if "hi" in message.content:
await message.reply("Hi!")
Whoops
You get the idea
He wanted help on how to reply
!e ```py
message = "him"
if "hi" in message:
print("in")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
in
ik ik message.content.split() exists
@maiden fable uhhh help
?
import discord
from discord.ext import commands
import random, os, asyncio
from discord.utils import get
bot = commands.Bot(command_prefix = "+")
@bot.command()
async def verify(ctx):
code = ("N6hT91")
await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")
def check(m):
return m.content == f"{code}" and m.channel == ctx.channel
member = ctx.author
await bot.wait_for("message", timeout=10, check=check)
role = get(member.server.roles, name="Test")
await ctx.send("test successful")
await ctx.author.add_roles(ctx.author, role)
bot.run(os.getenv("TOKEN"))
im still working on verify command and it wont give me the role. pls understand that i havent dealt with roles in a while so if its obvious i just dont realize it
it says member has no attribute server
Please don’t use replit
how to establish just one connection to my sqlite db and store it in a bot variable 😔
no
bot.db = sqlite3.connect()
It’s shares IPs it’s ass
im using aiosqlite
just use a task and set the count to 1
idc
or should I subclass Bot and add the variable(s) there?
you need to
await bot.add_roles
sift showed me an example a few days ago
i cant find it now 😔
then either use a task, event or the run (or was it start?) function
class Client(discord.Client):
async def setup_hook(self) -> None:
self.db = await connect(...)
member still has no attribute server
ok nvm found sift's message thanks
it's guild not server anymore if that's the issue
u can do something like this
async with aiomysql.connect() as con:
bot.var = con
if it can be used as a cm
well
that makes no sense, guilded is a different app XD
Just assuming, but wouldn't the context manager close the connection when exiting
So, in some cases using bot.var in this case, would be closed already
discord py changed its functionning so now most of the commands that uses .server changed to .guild
In this case you want to use it for the life-time of the bot, so you should open it without a context manager, then manually close inside of Bot.close
Which you can override to do so quite easily
ok but now its saying that bot has no attribute add_roles
i dont think so, it will close after the bot is shut down if ur using it with startup
i dont think its the same reason
what i mean is something like this
bot = ur bot
async with bot:
async with aio...:
bot.var = ...
bot.start()
Ah that makes more sense
But nesting the context managers just look weird IMO
But then again, not even sure if discord.py actually adds the signal callbacks correctly to handle SIGTERM (On windows that is)
@lofty pecan
what?
@slate swan How can I rewrite the slash commands? What to import? I tried googling it but couldn't find anything that helped me out
show code
use dpy 2.0 or a fork
install discord-py-slash-commands
No
like as a package
Still no
import discord
from discord.ext import commands
import random, os, asyncio
from discord.utils import get
bot = commands.Bot(command_prefix = "+")
@bot.command()
async def verify(ctx):
code = ("N6hT91")
await ctx.send(f"**Please repeat the following phrase:**\n\n{code}")
def check(m):
return m.content == f"{code}" and m.channel == ctx.channel
member = ctx.author
await bot.wait_for("message", timeout=10, check=check)
role = get(member.guild.roles, id="965658220830007387")
await ctx.send("test successful")
await member.add_roles(member, role)
bot.run(os.getenv("TOKEN"))
i changed to id and it still didnt work
just do member.add_roles(discord.Object(role_id_here))
Also IDs are int and not string
ooohhh
thx so much that finally worked!
just installed dpy 2.0
Cool
Oh cool.
pip install discord-py-slash-commands
not plural command
singular, discord-py-slash-command
gtg too so dm me if you have any more trouble
ill get back to you later
pip install discord-py-slash-command
idk bro works for me
ok
how can i make it where if you put a certain word in your status it sends a message and adds a role and if you remove that word it removes role and sends a message
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Hello, I am trying to get my bot to auto-emoji react to the new member message, I have the following code, not working - where am I going wrong? 😦
@client.event
async def wavehello(ctx, messageid: int):
channel = client.get_channel(-----------------)
await ctx.fetch_message(messageid)
message = await channel.fetch_message(channel.last_message_id)
emoji = 'wave'
await message.add_reaction(emoji)
how to make the participant 's profile show the time in the voice ? Do you need a time module and a datetime package for this ?
I'm having errors starting my bot, I have no code exept the code to start it up
Prob have that be in the on_member_join event ig
Then wait for a bit while the msg is sent, or make your own custom welcome
how do i fix this?
Read the last line of the traceback
I'm getting this error when running index.py file "AttributeError: module 'discord' has no attribute 'app_commands' please help
AttributeError: 'NoneType' object has no attribute 'strip'?
i know NOTHING about python, im just following a guide
Sums up abt half the people here unfortunately
I have this currently:
@client.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='Skritt Recruit')
await member.add_roles(role)
channel = client.get_channel(---)
await channel.send(f'{member.mention} just joined us! :slight_smile:')
welcomemessage = f"Hello"
embed = discord.Embed(title='Welcome!',
description=welcomemessage,
color=0xdb4b3c)
button = manage_components.create_button(style=ButtonStyle.URL, label="Check out the events!",
url=f'https://discord.com/channels/{--}/{--}')
action_row = manage_components.create_actionrow(button)
await member.send(embed=embed, components=[action_row])
for channel in member.guild.channels:
if channel.name.startswith('Total'):
await channel.edit(name=f'Total Members: {member.guild.member_count}')
message = await ((---).fetch_message(---).last_message_id)
emoji = '\n{WAVING HAND SIGN}'
await message.add_reaction(emoji)
Doesn't seem to add a reaction to the automatic message send by discord when someone joins
i just want a bot to use lol
could you run pip show discord.py and tell us which version you use?
@winged boneAttributeError: 'NoneType' object has no attribute 'strip'?
dm me and ill show you my code
nobody's stealing it here anyways too
i cant keep my pics from not being deleted
from os import getenv
from dotenv import load_dotenv
from discord import Client
client = Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord.')
load_dotenv()
client.run(getenv('TOKEN'))
there's my code
!code
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.
your issue is?
He posted the error above
Traceback (most recent call last):
File "C:\Users\User\Documents\CookieDiscordBoty\main.py", line 13, in <module>
client.run(getenv('TOKEN'))
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 631, in run
return future.result()
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 610, in runner
await self.start(*args, **kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 573, in start
await self.login(*args)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 424, in login
await self.http.static_login(token.strip())
AttributeError: 'NoneType' object has no attribute 'strip'
i can you show my ENV if you want
yeah but hide the token
@slate swan
@weak gyro
what
how can I remove the underscore ?
from PIL import Image, ImageFont, ImageDraw
what
do i put that in my .env?
why use an env in vsc? github pushes?
@weak gyro
I also wanted to make a discord bot before I knew Python, you run into obstacles all the time. I recommend that you do an introduction to Python first. This is a free online "book": https://automatetheboringstuff.com/
no.....
bot.run(getenv('DISCORD_TOKEN'))```
Traceback (most recent call last):
File "C:\Users\User\Documents\CookieDiscordBoty\main.py", line 13, in <module>
bot.run(getenv('DISCORD_TOKEN'))
NameError: name 'bot' is not defined
sorry, client.run
@weak gyro ahem
ight
do i replace token with my token?
how can I remove the underscore ?
from PIL import Image, ImageFont, ImageDraw
just the command where it is used works in in this line that I throw off all the words except from and import are underlined in yellow
PIL isn't a part of python's standard package, u need to install it pip install pillow
Hello, I don't understand what the problem is. Can you help?
PS D:\discord.py> & C:/Users/user/AppData/Local/Programs/Python/Python310/python.exe d:/discord.py/main.py
Testing Bot Готов к работе!
Ignoring exception in command ban:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 195, in convert
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "@gritty orchid я так решил" not found.
how to add custom emoji from url?
Basically, the member doesn't exist
In the server
It is there, but the bot does not see it....
As in they're probably not in the server
Hmm
Read the error message
You supplied the right id/name etc to the function?
from unicodedata import name
import discord
from discord.ext import commands
from pymongo import MongoClient
import os
class Ban(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(administrator = True)
async def ban(ctx, user, *, member: discord.Member,reason=None,):
await member.ban(reason=reason)
emb = discord.Embed(title='Забанен', color=0xff0000)
emb.add_field(name='Модератор', value=ctx.author, inline=False)
emb.add_field(name='Участник', value=member.mention, inline=False)
emb.add_field(name='Причина', value=reason, inline=False)
await member.send(f'Вы были забанены на сервере {name}. Модератор: {ctx.author}. Причина: {reason}.')
def setup(bot):
bot.add_cog(Ban(bot))
full code
hm seems like it didn't split the arguments correctly
could you remove the user parameter of the command and try again?
Seems like this is redundant
Hi there, so my bot runs thanks to a script, but I was wondering if there was a way I could send message directly inside the console in channel the bot has access to
Then how do I indicate on which server it was banned?
So you type in some message into the console and it sends it to a channel?
Could be difficult because you shouldn't block the asyncio loop. But I think there are various discord.py debuggers which allow you to input code on the fly
oke
I don't quite understand you. It looks like you're not using user at all though, so it shouldn't make a difference
Could you try it?
I have a problem
from discord import
is not working for me
can someone please help me with it
@slate swanI ended up degrading to python 3.9, and it fixed it, now the bot is online
but, how do I make it say things now
how would that change something?
because of pipes?
can someone give me an example of a custom check in events?
hi guys i have the redirect link to add my bot to the server but it isnt working
if i want automod to be disabled, the event should be disabled guild wide, so how would that look like
@client.command(pass_context=True)
async def ping(ctx, message: str, amount: int):
pingscore = 0
while pingscore != amount:
await ctx.send(message)
pingscore = pingscore + 1```
i learning how to make discord bots on python, i made command that will ping someone, how to make command that will immediately stop pinging without waiting for the end of the cycle?
I'm gonna say one word, that's what your bot will be from the discord API
banned
temporarily
it's gonna be ratelimited
how do i do slash commands do a command thats setup as .work to be /work as a app command?
without fully recoding the command can i do a sub command
im trying to add my bot to a friends server but its not adding for whatever reason
he has a react to verify for the server
could that cause issue of my bot not being able to join
oh yeah its getting stuck in the verify to react channel
@verbal silo
how can i use this in my command? i'm using ctx
this one is in my on_message
if not message.attachments:
ctx.message.attachments
aight thanks
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
when making a bot for multiple guilds is there anything different needed to allow commands to run without delays (waiting for commands to finish in other servers)
Welcome to async programming.
im assuming with the async functions its no needed?
but if any httpx requests i gotta user the async client
Indeed but not to be mistaken, there are still some sync code like for loops and while loops, use tasks for those. A lot of people also mix sync libraries with discord.py.
Thus aiohttp
httpx have a built in async request?, or is aiohttp better?
!pypi httpx
im using httpx, not normal requests atm
They are both pretty solid.
sound, was hoping i didnt need to change haha
HTTPX Has both Sync and Async clients
Quick question. I have a bot send a message in my server that should ping me. But instead, it just says has text. It's not pinging me like you would think it would. Does anyone know how I can actually make him ping me?
See. Wait
hold on
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
Or @vagrant tree
How do I fix "missing 1 required keyword-only argument: 'intents' error
class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
New in version 1.5...
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
As you can see it's a required arg
Yeah but what the final command looks like
Hey @verbal silo!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
What intent do I put and where someone please help - https://paste.pythondiscord.com/miwiyaxoke
client = discord.Client(intents=Intents())
Same error I think It may need the prefix too.
Hey there, is there a way using sqlite3 to get an image in the database and then fetch it to use it in an embed
I don't recommend it but you can convert an image to base64 then decode it again.
should I just with wait_for get the message link ?
if the message get deleted it's bad tho
But you are making slash commands?
people are asked to give the image of the character they're making a card about
but if they just put the image it doesn't take the link
so i could use the message link I guess
Can you please open the link I sent to see full script
Then use the attachment.
I did.
and does sql handle that?
I'm still trying to Rewrite all my code to the D.PY 2.0 version but only the help command works can someone tell me why? There are no errors using the other commands
Not originally but like I said you can convert an img to base64 if you want to do it anyways.
mmh
Where do you think it breaks?
Idk the help command is in the middle of the code but only that works, the stuff above and bellow doesnt, I dont have a clue why its not working
You got an on_message?
Not at the time
i've got my new bot online, how do i make commands and make it talk?
like commands and stuff
Are you asking how to make discord commands?
yeah
You should consider having a look at YouTube tutorials and the documentation of discord py then
That's what I did
how to count how much time a participant spent in voice ?
when i do $ping it doesnt do anything
Is there any way to send a discord.Message object, instead of specifying content, attachments, embeds, etc?
from os import getenv
from dotenv import load_dotenv
from discord import Client
client = Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord.')
load_dotenv()
client.run(getenv('DISCORD_TOKEN'))
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot is online")
@bot.command()
async def ping(ctx: commands.Context):
await ctx.send("pong!")
bot.run("DISCORD_TOKEN")
bruh
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
what did i do wrog in the code though
Never had that kind of 'error'?
uhm...
what
I feel bad for him if we don't tell him
i have this command and it's not sending anything and there's no error in console
@client.command()
@commands.cooldown(1, 120, commands.BucketType.user)
@commands.dm_only()
async def confess(ctx, *, coss):
if str(ctx.author.id) in blacklist:
await ctx.send("You have been blacklisted for a non-determained amount of time")
return
if not ctx.message.attachments:
channel=client.get_channel(954816338755457104)
confess=client.get_channel(931103626741563422)
embed=discord.Embed(
color=0x010914, description=f"`{coss}`")
embed.set_footer(text="DM /confess <content>", icon_url={ctx.guild.icon_url})
await ctx.send('Confession has been sent!')
await channel.send(f"{ctx.author} - {ctx.author.id}\n{coss}`")
await confess.send(embed=embed)
if ctx.message.attachments:
channel=client.get_channel(954816338755457104)
confess=client.get_channel(931103626741563422)
embed2=discord.Embed(color=0x010914, description=f"{coss}")
embed.set_image(url=ctx.message.attachments[0].url)
await confess.send(embed=embed2)
await ctx.send('Confession has been sent!')
await channel.send(f"{ctx.author} - {ctx.author.id}\n{coss}\n{ctx.message.attachments[0].url}")
how can i fix it?
@weak gyro Do you know Python? or did you just started discord.py without any knowledge of python
add prints
aight wait
Then see till where it gets
no knowledge
Then learn python first
can you tell me how to fixx my code, first please
from os import getenv
from dotenv import load_dotenv
from discord import Client
client = Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord.')
load_dotenv()
client.run(getenv('DISCORD_TOKEN'))
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot is online")
@bot.command()
async def ping(ctx: commands.Context):
await ctx.send("pong!")
bot.run("DISCORD_TOKEN")
!code
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.
im using backticks
What
from os import getenv
from dotenv import load_dotenv
from discord import Client
client = Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord.')
load_dotenv()
client.run(getenv('DISCORD_TOKEN'))
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot is online")
@bot.command()
async def ping(ctx: commands.Context):
await ctx.send("pong!")
bot.run("DISCORD_TOKEN")
oh
There are too many issues man
If you would know at least the basics of python
Then you can solve this easily
the argument work before i define the channel client.get_channel but after that it won't work anymore.
Look at this example:
@client.event()
```py
And you got:
```py
@bot.event()
``` See any difference?
Can you send me it with the prints and tell me till where it prints
Do you get this issue?
what should i print the argument?
my bad, it work after i define the channel.. it won't work after the embed i made.
not really
Hm alright let me take a look
Then learn python please
I don't see any issues
would you mind running it?, it won't really work in mine and there's no error
Sure I'm setting it up
aight thankss
@junior vergegot it fixed
from os import getenv
from dotenv import load_dotenv
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord.')
load_dotenv()
bot.run(getenv('DISCORD_TOKEN'))
@bot.event
async def on_ready():
print("bot is online")
@bot.command()
async def ping(ctx: commands.Context):
await ctx.send("pong!")
bot.run("DISCORD_TOKEN")
i was helped but im learning
I have a working discord bot online if anyone needs to look at it for help, as long as I can post links
Python discord bot. Currently has a few random things, add to your server to see them(or fork, that works too)
here is bot link
https://discord.com/api/oauth2/authorize?client_id=963567504674930768&permissions=240704&scope=bot
Ah the link worked
Didn't know if it would be auto deleted
Should be a file button in the top left of the run box
I'm using UptimeRobot and Replit to create a 24/7 Discord bot, but he keeps going down. I've watched a few tutorials, and I don't think I'm doing anything wrong. Will UptimeRobot sometimes just not work??
Because replit is not a host
It's meant for running quick tests and dispose of later
not for long-running processes like a discord bot
But it works for one of my bots...
That doesn't mean it's good
oooh
Replit is very unreliable and is not a host
man, that's disappointing
Consider getting an actual host
Where would I do that?
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = 'Отсутствует'):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
print("работает")
if member is None:
await ctx.send("Выберите участника")
return
if warnings is None:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'Отсутствует'))
base.commit()
print(2222)
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
else:
cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}")
how to make it so that if the reason is not specified, then Отсутствует is not written in the chat?
They could but their infrastructure for the time being is not meant for that
Also the only people really doing that is new users to making discord bots
so it's really not all that much
Wait, so if Replit is unreliable, then why does one of my bots always seem to be online?
@vagrant tree take a look at this: https://github.com/python-discord/site/blob/main/pydis_site/apps/content/resources/guides/python-guides/vps-services.md
pythondiscord.com - A Django and Bulma web application. - site/vps-services.md at main · python-discord/site
Yeah they have nodejs
Because it's unreliable
Sometime's it'll work and sometimes it won't
mk
Help
One of reasons to not be using replit as a host
It's really just a use and throw quick test platform
ok, but what about the error?
Hey @mortal dove!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
best discord bot guides???
There is an error under the code @slate swan
and resources?
thanks!
Can you help me or can't you? @slate swan
https://paste.ofcode.org/bqYvxm7aRUbNyCeH9P2yDN Can anyone help? The traceback doesn't mention any specific code that would cause the error, and the command has worked before.
Im pretty sure that’s not the full error
There we are
Hm?
Looks like the issue is in the help command
But you already narrowed it down to that I see
You’re referring to “self.context “ but I’m not seeing where it’s being defined
It's defined in self because the main class inherits from commands.HelpCommand
https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=commands helpcommand#discord.ext.commands.HelpCommand idk how to use bot tags so here's the full link
it gives you a context attribute
Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB
Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo
I've posted the actual loop itself and also the first function. any help would be greatly appreciated.
Could it be because im using aysnc tasks?
does anyone here use heroku?
How do you host a bot on your raspberry. Online ressources are lacking
What is the requirements, the set up, how do you put the bot on the RP, and so on
Where did you find the instructions @final pumice lol
Is it possible to have multiple different colors on one line?
All i can find is the syntax different colors?
@slate swan am i being a mong but i cant seem to get it working 😄 ?
←[31m why does this appear when I run a .py file?
@sick birch do you know where you can find info because in the command profile you can add the ability to see how many participants were in the voice for all the time on the server?
Hello! How do I use unix timestamps when sending a message.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Im not understanding
well use time.time() to get the current unix timestamp
and then send the result from it.
Show
Show
look into SSH
😫 😩 😩 😩
im doing a discord bot with a command that interacts with api with a request.get to get statistics
but i need to format it through json.loads or json.dumps(i cant remember)
but im not sure how do this
json.loads
ok sweet
no
await ctx.send(r.get(f'https://api-mainnet.magiceden.dev/v2/collections/{me}/stats').text), json.loads('floorPrice')
so far ive got that on one line
json.loads = loads a string into a dict
json.dumps = dumps a dictionary
ahhhh
so right now
{"symbol":"sea_shanties","floorPrice":8600000000,"listedCount":46,"avgPrice24hr":8850000000,"volumeAll":46204571198672}
this is the result of my command
so i want to json.loads the floorprice and just receieve that
and divide it by however many 0s
idk how to do multiple lines of code with discord bot command coding
and not sure if i can do all that on one line?
👀
async def magic(ctx, *, me):
await ctx.send(r.get(f'https://api-mainnet.magiceden.dev/v2/collections/{me}/stats').text), json.loads('floorPrice')
hi jonathan
Hi hazbob
so right now ive got all that on one line of code
but i need to store the r.get request into object/variable?
cant remember what an object or variable is
im rambling through discord😂
Can anyone help? I'm making a help command, and get this error. Nor sure what I'm doing wrong, and I don't get any helpful things from traceback.
Code & error: https://paste.ofcode.org/bqYvxm7aRUbNyCeH9P2yDN
yes, that is the entire error
I also tried replacing the entire command body with just pass, and it still gives the same error.
using discord.py
why don't you just do r.get(...).json() then index the dictionary that the json method returns?
ah ok didnt know that was possible
ty ill give that a go
👍
how would i write the r.get
is it apart of the @native granite
oh sorry
async def magic(ctx, *, me):
magiceden = r.get(f"https://api-mainnet.magiceden.dev/v2/collections/{me}/stats')").json()
await ctx.send(magiceden)
how do i index sorry
also when i do the command above nothing is sent through to discord
>>> dict = {'floorPrice': 10}
>>> dict['floorPrice']
10
!code
async def magic(ctx, *, me):
magiceden = r.get(f"https://api-mainnet.magiceden.dev/v2/collections/{me}/stats')").json()
dict = {'floorPrice': '10'}
await ctx.send(magiceden)
when i run the magic command nothing is sending through to discord
im not sure if i have the wrong format of running multiple lines of code for discord.py
```py
(... your code here)
```
Can I see your bot constructor?
what is a constructor sorry?
im v new
but yes
dw, it's the line that goes like
bot = commands.Bot(
#...
)
bot = commands.Bot(command_prefix='!')
its working for all my single line commands, like ctx.send(discord.File)
just this multiple line code im trying to do
isnt sendind
magiceden is the dictionary you're supposed to index
no errors?
oh im not sure about the message.intents
oh yeah looks to be a json decode error
not exactly sure what that means
Theres an extra parenthesis/single quote in the URL
what can i do about this? AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
You can’t use the loop property or start tasks.loop in a synchronous function
can i in a cog?
i have a quart server and discord bot does anyone know how i can send a message in a channel when someone visits the quart page
so can i do sumthing like this? asyncio.create_loop(update_stats(bot))
bot.loop.create_task?
if variable isnt in database:
create one
else:
pass
```how do u do this
Yes but I still got to figure out how to get this to work in a async function because what I have apparently will not
if db[f'{userid}{itemname}] isnt in database:
db[f'{userid}{itemname}] = 0
else:
pass
Override the cogs cog_load with an async func and do it there
Then override the bots setup_hook
I don't understand what that has to do with it though
Because u can’t use the loop in a non async function
Ooo
And setup_hook is async and called at the start
Nor do I know how to overwrite it 😑
Subclass
Yeah I think I'll just delete this for now
Alrigt
This seems like a problem that top.gg can help me with at a later date because it's their API
Yes but the loop relates back to their API
Yeah really it uses their API that's what the loop is for
subclassing is simple if you wanna try it
from discord.ext import commands
class Bot(commands.Bot):
async def setup_hook(self):
self.loop.create_task(...)
bot = Bot(...)
so ```py
class Bot(commands.Bot):
async def setup_hook(self):
dbl_token = "Top.gg token" # set this to your bot's Top.gg token
bot.topggpy = topgg.DBLClient(bot, dbl_token)
"""This function runs every 30 minutes to automatically update your server count."""
try:
await bot.topggpy.post_guild_count()
print(f"Posted server count ({bot.topggpy.guild_count})")
except Exception as e:
print(f"Failed to post server count\n{e.__class__.__name__}: {e}")
self.loop.create_task(update_stats(self.bot))
should work
It seems to stop the bot from completely running though
just remember to use this new Bot instead of commands.Bot
ohh yeah
do you need to post it right then or can u just post it in update_stats
@sly hamlet
Needs to be posted probably in the run function
!d not
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
thanks
no so will update_stats post the bot count? If yes then you dont need to use bot.topggpy.post_guild_count() here
Where are you getting that from I do not have a function called that
in the self.loop.create_task
It probably needs to be changed to setup hook
why would you subclass the bot class over using the AbstractEventLoop
It is plus that doesn't even work
what
That sub class doesn't even work we still get the same error
ah youre talking about that and what error
There’s an wait_until_ready lockout
Probably from post_guild_count
So remove that part if update_stats posts
post guild count method takes the number of guilds
have you learnt python basics before making a discord bot?
Nope
it's update_stats(self) since self is the 'bot'
Will it not use bot.guilds?
It takes the bot
doesn't matter how you get it, but the argument needs to be supplied and they are kot
*not
So remove self?
no.. remove .bot
I’m surprised topgg won’t do it for you
i did it
i thought u cant
if f'{userid}{armor}' not in db:
```it just look weird but it works
true, since it has the bot class it can easily access the guilds property
I don't see at all where that is
self.loop.create_task(update_stats(self.bot))
Actually it does, it's a Optional argument, they examples used them
But this needs to be down inside my run function otherwise the bot does not work
Oh ok makes sense
Then self would not work and it would need to be bot
thats not what I meant
it's like doing ```py
bot = Bot()
bot.bot
In this class self is the bot object
But that piece of code that runs it does not need to be up there it needs to be inside the run function of the bot
So instead of bot for the function I need self
run is not async so you can’t use loop. setup_hook gets called before it logs on so same as if u were to call it in start
My run function is a async
Well then u can use loop there
That's what I'm doing but inside of the setup hook we still get the same error and it still does not work
Show code for run
class Bot(commands.Bot):
async def setup_hook(self):
dbl_token = "" # set this to your bot's Top.gg token
bot.topggpy = topgg.DBLClient(bot, dbl_token)
"""This function runs every 30 minutes to automatically update your server count."""
try:
await self.topggpy.post_guild_count()
print(f"Posted server count ({bot.topggpy.guild_count})")
except Exception as e:
print(f"Failed to post server count\n{e.__class__.__name__}: {e}")
async def sync_commands(bot):
await bot.wait_until_ready()
await bot.tree.sync()
for guild in bot.guilds:
await bot.tree.sync(guild=guild)
async def main():
await bot.load_extension('cogs.botut')
await bot.load_extension('cogs.fun')
await bot.load_extension('cogs.nsfw')
await bot.load_extension('cogs.pic')
await bot.load_extension('cogs.helpmenu')
await bot.load_extension('cogs.admin')
await bot.load_extension('cogs.ut')
await bot.load_extension('cogs.mute')
await bot.load_extension('cogs.testmusic')
asyncio.create_task(sync_commands(bot))
bot.loop.create_task(setup_hook(bot))
async with bot:
await bot.start("")```
i forgot how to make emoji into letters again
you don't need to create a task for the setup_hook, discord.py already does that for you
something like this
<:pogchop:917408218240671755>
why not use a for loop to load cogs?
So what do I need to do?
remove bot.loop.create_task(setup_hook(bot))
and whats bot in the main function?
Doing that makes it not work again
because bot its undefined
So that's going to stop the entire bot from working and not even run with no error
youre subclassing bot so your bot object is your own class so you would need to access an instance with self
that would raise an error most likely
It doesn't
The only thing that happens is that my cogs load nothing else happens the bot will not run
Try removing the post guild count in the setup hook
But it needs it in order to post it
Then what is update_stats
So if u have that then why post the guild count
If that does already
No I do not
This is literally my entire main file
Hey folks! Bit of a noob-esque question here: which library should I use? There's just so many forks out there! I've programmed a bot in discord.py before the discontinuation of it, so anything similar would be nice. I was thinking pycord, but will I make the right call with that?
At the bottom
Oh well nvm
It was in the old code



