#discord-bots
1 messages · Page 616 of 1
no
the key needs to be the activity type
please spend a little time learning python this is the last time i will help with these kind of stuff
How do i check if a user is the guild owner ?
i don't wanna do ```py
@commands.has_permissions(administrator=True)
!d discord.Guild.owner
property owner: Optional[discord.member.Member]```
The member that owns the guild.
how do i make the bot go offline without closing vs code?
close the process of python
how?
ctrl + c press that while focusing the terminal window
otherwise you have to open the task manager and search for a process named python
I have this command, but when I try to send a emoji from another server using this it wont work as I don't have nitro and it tried to make it emoji before sending it. So how could I sent a emoji using <:name:id> or smth else? ```py
@commands.command()
@commands.cooldown(1, 10)
async def echo(self, ctx, channel: Optional[discord.TextChannel] = None, *, message: str):
'''Will be sending message to specific channel NOTE: should only be used in moderation channels'''
await ctx.message.delete()
if channel is None:
channel = ctx.channel
await channel.send(f"{message}")
Is the bot in the server where the emoji is located?
In another server that I own
So yes
https://wtools.io/paste-code/b7T0 Anyone know why it can't change the square to the mark? I trying to make tictactoe.
global variables :/
await ctx.send("It is <@" + str(player1.id) + ">'s turn.")
consider using f-strings and discord.Member.mention
!tags fstring
Okay, What do i have to change in global variables then?
sql-fstring
f-strings
you shouldnt need global variables at all. you have it inside a class. set them as attributes of the class
Okay I will try.
also follow the pep8 style guide
I will update(cry for help) you if I fail
instead of thisCasing use this_casing
snake case
I have a problem, when the embed sends this review product, if the user indicates the reviewed product there are no spaces for example: c! review DS Test 5 stars test
DS Test only puts DS and then Test in stars, despite having put * in the parameters
code
title = f 'Product Review',
description = f'Prodotto: {product} \ n Stars: {stars} \ n Rating: {message} ')```
def convert(argument):
args = argument.lower()
matches = re.findall(time_regex, args)
time = 0
for key, value in matches:
try:
time += time_dict[value] * float(key)
except KeyError:
raise commands.BadArgument(
f"{value} is an invalid time key! h|m|s|d are valid arguments"
)
except ValueError:
raise commands.BadArgument(f"{key} is not a number!")
return round(time)```
```py
while True:
zeit = await self.bot.wait_for('message', check=check, timeout=60.0)
time = convert(zeit.content)``` how can i check if zeit.content is a valid time format?
how do i make automatic restarts for my bot
Wdym?
You did \ n instead of \n
Using the dpys tasks framework
need some help
I tried to do, guild = discord.guild.Guild, then answer = guild.member_count, But it just says i need to have tracemalloc enabled, i enabled it, then it just said that that attribute doesn't exist
What do you need?
Let’s see your code
nvm
Oh
Well it should have no problem with \n
can any1 decent at replacing lines help in #help-falafel
!e
product = ‘test’
stars = 5
message = ‘ok’
embed = discord.Embed (
title = f 'Product Review',
description = f'Prodotto: {product} \ n Stars: {stars} \ n Rating: {message} ')
@velvet tinsel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | product = “test”
003 | ^
004 | SyntaxError: invalid character '“' (U+201C)
!e
product = ‘test’
stars = 5
message = ‘ok’
embed = discord.Embed (
title = f 'Product Review',
description = f'Prodotto: {product} \ n Stars: {stars} \ n Rating: {message} ')
@velvet tinsel :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | product = ‘test’
003 | ^
004 | SyntaxError: invalid character '‘' (U+2018)
Wth is wrong
how to make a string a discord.PartialEmoji
the quotes need to be ' or " characters not ur fancy ‘ or ’ unicode characters
Oh
can any1 decent at replacing lines help in #help-falafel
I’m in
Hey! is it posible to show in what position the channel is, for example, i create a ticket and thres 4 before me, and the bot answers your ticket is the number 5.
!d discord.TextChannel.position
The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0.
but idk how to if its in a category
How should i start? no idea
umm
just an example so i can make an idea if you want
How would you make a command that would be like !invite 1 that you would get a 1 use invite link?
You are missing Administrator permission(s) to run this command.
How can I transfer this into a ctx.send instead of spitting an error?
This is my code:
@bot.command(name="verify")
@has_permissions(administrator=True)
async def verify(ctx):
try:
await ctx.message.delete()
# Sum code here
except:
await ctx.send(f"{ctx.author.mention} U don't have perms to do that", delete_after=20)```
hewo?
@verify.error
async def verify_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send(f"{ctx.author.mention} U don't have perms to do that", delete_after=20)
idk how listen works sorry
np
put underneath command btw
There are some docs
ik but i dont need it
O k
Use an error handler
thx
Simple Error Handling for ext.commands - discord.py - error_handler.py
Thanks dud
Thanks to Sherlock for introducing this to me ^_^
^o^
It works really well, error handlers
I dont have my PC with me but with some basic knowledge you get the idea
try/except doesn’t work
trust me I used them before
yes I saw that..
@slate swan I’m not an expert, I’m using my own experiences. Can you please confirm?
Also does it have to be in a seperate cogs file? Or can I paste it in my main.py aswell
try/except dont work for discord errors
i tried also lol
Didnt we all
lol
😂
although for webhooks i have got away with except Exception:
but when i tried to do specific error handling it didnt work
taught myself
Book? Tutorial?
i dont really know it that well, my friend sent me his discord bot and i just kept working off it
nah i just learnt as i made stuff
i followed various stuff online as i tried make stuff
but nothing structured
i like python coz its pretty easy to figure out
Look at an OSC and just say ‘ok’
Or look at an error and instantly find the solution
guys I have an AttributeError
Me: look up the docs * insert doc link here * it doesnt exist in the class
Hi ! I'm using this meme command code ```py
async def meme(self, ctx):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://www.reddit.com/r/memes/new.json?sort=hot") as response2:
j = await response2.json()
data = j["data"]["children"][random.randint(0, 25)]["data"]
image_url = data["url"]
title = data["title"]
em = discord.Embed(description=f"{title}", color=invisible_color)
em.set_image(url=image_url)
em.set_footer(text=footertext, icon_url=ctx.author.avatar_url)
await ctx.send(embed=em)
And sometimes i get this error ```
data = j["data"]["children"][random.randint(0, 25)]["data"]
IndexError: list index out of range
What does it mean ? are there less than 25 choices ?
Try printing data (actually screw this try going through each one 0 - 25 and find out which number hits an error)
(On a separate piece of code)
Or print it in your thing
There may be less than 25 choices, but you have to confirm
i think that's the problem
Oh why did I not think of that 
Thinking about it that seemed like the most obvious thing
actually u need to do len(j['data']['children'])
i tried to print len(data) and i got 109
actually im confused
I think it’s because he only printed data
it was the rand.int inside the dictonary parsing but it does make sense what i said lol
If len() doesn’t work possibly we can make a while loop to see which number hits an error but that’s just how I work and it’s the longer way around
I think maybe len() would work perfectly
Found it. Python indexing starts at 0, so if i want 25 choices i have to put 24
data = j["data"]["children"][random.randint(0, 24)]["data"] works
Yes
Lol
Right going to sleep bye
Could someone help me? I have an if statement and then a bunch of elifs but it never cycles through to the elifs..
The code is like this:
@client.command()
async def pack(ctx, dino):
dino = str(dino)
if dino == "apa" or "apato":
await ctx.send("Apa...")
elif dino == "lurd" or "lurdu":
await ctx.send("Lurd...")
If I pass in dino as lurd, it still outputs 'Apa...'
!or
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.")
In Python, you should have complete instructions on both sides of the logical operator
if dino == "apa" or "apato": turns to -> if dino == "apa" or dino == "apato":
and that should stop my elifs from being skipped?
your if condition is always true, the way you have it now
because it works when in solo code, but not when in a discord bot
so the elif is never even evaluated
Why is it always true?
The first part of this condition is fine
if dino == "apa":
The second part always evaluates to True
!e
print(bool("apato"))
@full lily :white_check_mark: Your eval job has completed with return code 0.
True
@lofty cedar
Since non empty strings are Truthy
so what you're actually asking python is Is the variable dino equal to the string "apa", OR is the string "apato" non empty?
Read the embed I sent above, it explains everything
By using a .env file
How can I check if a button is pressed by the custom_ID of that component?
can any1 help me fix it?```py
error4 = f"ERROR | Correct usage: {ctx.prefix}{ctx.command.name} {ctx.command.signature}."
if isinstance(error, MissingRequiredArgument):
await ctx.reply(error4)
error: AttributeError: 'NoneType' object has no attribute 'name'
ok
The bot is sending error to the terminal again...
AttributeError: 'NoneType' object has no attribute 'signature'
Send the command
is the same
.
but without the .name
Send me the
@bot.command()
async def ...```
@bot.event
async def on_command_error(ctx, error):
Hi Im trying to make a bot that so the person who is hosting the bot, when they put input into the terminal/console, it will send a message in a channel. Kind of like a Discord command but from the person whos hosting the bot. I found a way to asynchronously look for input but I dont know where to put it
userInput = await aioconsole.ainput()
Why don't you do it via a seperate channel that only you can see?
I have my reasons lol
ok lol
Is there any one that could help make a verification system?
is there a function to return the user/members current channel id?
Any body around How do i make my discord bot send dm's to one specific user on my server
@bot.command() @commands.has_permissions(administrator=True) async def r1(ctx, user: discord.User, *, message=None): message = message or "Please come to the flooding room." await ctx.send(f"Message Sent") await user.send(message)
is there anyway i can put there user ID inside the command so it just sends to the one person
@old gate Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
oops
I tried it and it worked for me
all i did was remove the *
and it still works with the *
what does that do i just want to put the users id in there so it send him the message only
i don't get what your problem is
Trying to only send dm's to one person
is the person in the server with the bot?
yep
im just trying to put there user id in there so i dont have to when i run the command it will just send him the dm
this worked for me, i just changed the name of the command name
woah
did it work?
Nope
does it give you an error?
a bunch
can you send a screenshot of the last error?
if "Enabled" in check and len(message.mentions) >= 4:
await message.add_reaction(":white_check_mark:")
so it'll add the reaction if I set 4 to 2 or below. but for some reason it won't detect anything past 2
anyone have a clue why?
see if i run it without the id in it works fine
- dont want to have to always put his user name in
We are scambaiters that want to stop these evil criminals
I'm unsure if this is advertising or not. But, just in case - @hot cobalt
quite odd
Looks like advertising to me
Btw you should ping the moderator role as the mods say and not ping jack cause you dont know what hes doing or if he likes getting pinged only
Ah. I'm always afraid of pinging the moderators role.
Thats like being scared of the police
No need to be
<@&831776746206265384> dont know if you guys seen this message or are investigating it but this message looks like advertising to me
Yes you can
@old gate please don't advertise on our server
it isn't like that, although you're right that we prefer you ping the role
You can use a error decorator or in a try and except just do:
except discord.Fobidden:
I mean yeah but no one should be scared of getting a penalty because of pinging the mods that help keep this server in order
Sorry about that
sorry boss
Guys it's not advertising its a problem with our bot
How do i get it to only send to one person without having to input there name everytime i run the command line
the command it just ment to go to one person on my server
Like send a message to a member? When a command is invoked?
@bot.command()
@commands.has_permissions(administrator=True)
async def r1(ctx, user: discord.User, *, message=None):
message = message or "Please come to the flooding room."
await ctx.send(f"Message Sent")
await user.send(message)
@slate swan allot of exceptions in docs btw dont use bare exceptions as they raise for any error
what do i change inside that protion where i put his user id
To dm you use member.send
But nevermind cuz your using user
@old gate do you always one to send it to the same member?
yep
yep u got it friend 🙂
Also sorry i wasnt trying to advertise its just confusing
Get their id and send a dm
disnake.Embed(title="Shop Category: Event Ticket and More",description=f"- `/buy name: [item name] amount: [amount]`` to buy a item\n- Cardcoins: {cardcoin[0]:,}:card_coin:\n- Votecoins: {votecoin[0]:,}:vote_coin:",timestamp=datetime.datetime.utcnow(),color=blue)
``` why does this line show "int" object is not sub scriptable error?
ok i'll try it @slate swan ty
Yw
May i add you as a friend?
Sorry i dont add anybody from this server
Thats ok thats why i asked first thanks
Yw good luck!
@old gate sorry for the ping but i mostly like keeping all of the conversation in this channel if you need any help feel free to ping me or type in this channel
🙂 ty
Yw
I tried these for webhook and it didnt work
for webhook?
Yeah the webhook responses, sometimes webhook give u 404 or 403 and they show in console as those type of errors but i couldnt catch them with those
Idk never used webhooks
I wanted to detect if someone deleted the webhook
those are status codes
Yh i know i was tryna catch the corresponding discord error
I just use except Exception it was good enough it told me if webhook was deleted
Although false positives sometimes
Did you check the Discord API docs? They may have the specifics codes that go with certain issues like for instance a deleted webhook
Yeah im using library though for webhook
If i was doing webhook myself i could use the status codes and responses
But id rather dpy does the rate limiting
Any1?
bruno@bru-rdgz Braver_Bot]$ /bin/python /home/bruno/Documents/GitHub/Braver_Bot/bot_main/__main__.py
Traceback (most recent call last):
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/__main__.py", line 20, in <module>
bot.load_extension(filename)
File "/usr/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named '__Dev_Tools__'```
Got this error, here's the code:
import os
import discord
import discord.ext
from discord.ext import commands
from __holder__ import Discord_Token
# Declarations
bot = commands.Bot(command_prefix='-')
Token = Discord_Token
# Inits
async def on_ready():
print ('{} está online!'.format(bot.user))
for filename in os.listdir('./bot_extensions'):
if filename.endswith('.py'):
bot.load_extension(filename)
print('{} foi carregado!'.format(filename))
else:
pass
# Kickstarter
bot.run(Token)```
I genuinely have no idea on what's wrong with this, I've legit rewrote this code like 3 times and it's still giving the same error
have you tried doing:
bot.load_extension(filename[:-3])
it removes the .py from the end
Otherwise one of the extensions is showing a module __Dev_Tools__ which is not installed? at least that's what i gather from your error.
I've just tried this solution and it still doesn't work
and __Dev_Tools__ is my extension
disnake.Embed(title="Shop Category: Event Ticket and More",description=f"- `/buy name: [item name] amount: [amount]`` to buy a item\n- Cardcoins: {cardcoin[0]:,}:card_coin:\n- Votecoins: {votecoin[0]:,}:vote_coin:",timestamp=datetime.datetime.utcnow(),color=blue)
why does this line show "int" object is not sub scriptable error?
<Record vote_count=39> that is what it returns tho
try bot.load_extension(f"bot_extensions.{filename}")
Still doesn't work
It reads the file, but doesn't want to load in
well, your first issue was that it couldn't find the file, so it sounds like you've made progress
extensions require a setup function. did you add that?
Have a Setup function in the cog?
I do
what's your new error then?
still the same error
does it have ```py
bot.add_cog(CogClass)
ModuleNotFoundError: No module named '__Dev_Tools__' means it can't find the file @lofty mulch
bruh, wrong file
Done, created a dummy class so I can try to execute it
yep, still the same error
Traceback (most recent call last):
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/main.py", line 19, in <module>
bot.load_extension('{}'.format(filename))
File "/usr/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = import(parent_name, fromlist=['path'])
ModuleNotFoundError: No module named 'Dev_Tools'
# Imports
import discord
import discord.ext
import discord.ext.commands
from discord.ext import commands
# Declarations
bot = commands.Bot
# Classes
class Dummy(commands.Cog):
def __init__(self):
self.bot = bot
# Binder
def setup(bot):
bot.add_cog(Dummy)
test cog
the loading code
Inits
async def on_ready():
print ('{} está online!'.format(bot.user))
for filename in os.listdir('./bot_extensions'):
if filename.endswith('.py'):
bot.load_extension('{}'.format(filename))
print('{} foi carregado!'.format(filename))
else:
pass```
so you've been given 2 suggestions already: trim .py from the filename and add bot_extensions in front of your filename
Inits
async def on_ready():
print ('{} está online!'.format(bot.user))
for filename in os.listdir('./bot_extensions'):
if filename.endswith('.py'):
bot.load_extension(f"bot_extensions.{filename[:-3]}")
print('{} foi carregado!'.format(filename))
else:
pass
aand it still gave the same error
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/__main__.py", line 19, in <module>
bot.load_extension(f"bot_extensions.{filename[:-3]}")
File "/usr/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'bot_extensions'```
I think that the bot_extensions might be out of place, since it's prob recognizing the folder instead of the archive
Guys, my pycharm is dead
a few hours ago my bot was working just fine
now, it says that functions don't exist
and the message parameter for on_message doesn't exist?
nani?
of the file*
@lofty mulch I am mostly referencing the API docs: The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.
so, rename it to dev.tools
Question. I had made a command that would shuffle my bots activity based on a set list
@client.command()
async def shuffle(ctx):
poiu = random.choice(songs)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str(poiu)))
await ctx.send(f'I am now listening to: {poiu}')
This works, but before hand I tried await ctx.send(f'I am now listening to: {name}') and the result confused me. The activity changed to a song, but the bot said it was listening to a different song than it was actually listening to. I fixed this by replacing name with poiu but I want to know why they arent the same?
can you show your file/directory structure?
name is a keyword argument to the Activity class, which you set equal to poiu
Yeah so why didnt they display the same thing?
can you show the original code before you fixed it?
Yeah it was
@client.command()
async def shuffle(ctx):
poiu = random.choice(songs)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=str(poiu)))
await ctx.send(f'I am now listening to: {name}')
OS crashed out of nowhere
Reopening Vscode
maybe I'm blind, but I don't see you setting a variable called name in this function, only a keyword argument
do you have name = ... outside of this function, as a global variable? maybe it's reading that
No, I was reffering to it inside of client..change_presence() so maybe thats why?
Here's my file tree
right, but you aren't declaring a variable there, only providing a keyword argument
it's like you're making a new dog object like
dog = Dog(name="Fido")
Fido is a pretty cute name tbh
So why did it still choose a random thing from the songs? Ohhh wait… did it execute what poiu was instead of just using what it already was?
Why do you have it named dev.tools instead of dev_tools or something similar
cause of this
i think you misunderstood what that meant
if you had a file tree like
cogs/
foo.py
bot.py <- file the extension is being loaded in```you would load it like `bot.load_extension('cogs.foo')`
can you share your whole code?
There’s nothing that references either of those outside of the stuff I sent tho
disnake.Embed(title="Shop Category: Event Ticket and More",description=f"- `/buy name: [item name] amount: [amount]`` to buy a item\n- Cardcoins: {cardcoin[0]:,}:card_coin:\n- Votecoins: {votecoin[0]:,}:vote_coin:",timestamp=datetime.datetime.utcnow(),color=blue)
why does this line show "int" object is not sub scriptable error?
then you have committed some weird python magic
aka I have no idea

tf am I doing wrong?
for filename in os.listdir(path='/bot_main/bot_extensions'):
if filename.endswith('.py'):
bot.load_extension(f"bot_extensions.{filename[:-3]}")
print('{} foi carregado!'.format(filename))
else:
pass
Traceback (most recent call last):
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/__main__.py", line 17, in <module>
for filename in os.listdir(path='/bot_main/bot_extensions'):
FileNotFoundError: [Errno 2] No such file or directory: '/bot_main/bot_extensions'```
Tbh now just add the file names in a list and load them
ah
I swear, I have a harder time trying to connect the cogs rather than actually coding
If I could actually manage to somehow load them, I would
Add them in the same folder the main bot file is in
don't do for filename in os.listdir(path='/bot_main/bot_extensions'):
What should I do instead?
the ./bot_extensions is probably correct
What I think happened is when I tried to use name it just went with what poiu was defined as, which was to choose a random song. That’s good to know I suppose
Gave the same error, though. That's why I tried the path=
sure, but I'm explaining that change will not fix it
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/main.py", line 17, in <module>
for filename in os.listdir('./bot_extensions'):
FileNotFoundError: [Errno 2] No such file or directory: './bot_extensions
Are you using the your IDE terminal?
Like, to execute the file?
Yes.
Could you print the cwd?
Lemme see If I can
yeah, you need to be running this from within your bot directory
the . is a relative import
@cloud dawn can you help me lmao
!e print(1[0])
@cloud dawn :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'int' object is not subscriptable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'int' object is not subscriptable
You can't index an int.
for the cog, right?
The file that you want to import it in.
Should look something like print(os.getcwd())
/bin/python /home/bruno/Documents/GitHub/Braver_Bot/bot_main/main.py
wait, i didn't print
nvm
/home/bruno/Documents/GitHub/Braver_Bot
Here is it
Hmm okay could you do this aswell? print(os.listdir('./'))
But when I print it, this is what it returns
<Record vote_count=39>
then do os.listdir('./../bot_extensions')
traceback?
SyntaxError: unexpected EOF while parsing
That's because you need to extract that value, that is not done by indexing but with keywords.
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
ah, you want me to raise a exception and print a full traceback?
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/jishaku/features/python.py", line 149, in jsk_python
async for send, result in AsyncSender(executor):
File "/usr/local/lib/python3.9/dist-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "/usr/local/lib/python3.9/dist-packages/jishaku/repl/compilation.py", line 140, in traverse
async for send, result in AsyncSender(func(*self.args)):
File "/usr/local/lib/python3.9/dist-packages/jishaku/functools.py", line 109, in _internal
value = await base.asend(self.send_value)
File "<repl>", line 2, in _repl_coroutine
await _ctx.send(f"{cardcoin.balance:,}")
AttributeError: 'asyncpg.Record' object has no attribute 'balance'
``` is what happens when I add `.balance` after it
try
for filename in os.listdir('./bot_main/bot_extensions'):
if filename.endswith('.py'):
bot.load_extension(f"bot_extensions.{filename[:-3]}")
print('{} foi carregado!'.format(filename))
else:
pass
``` @lofty mulch
Well it should throw a traceback by default.
I think he already go trough the loading of the cogs but this is an error inside a cog.
Traceback (most recent call last):
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/main.py", line 19, in <module>
bot.load_extension(f"bot_extensions.{filename[:-3]}")
File "/usr/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = import(parent_name, fromlist=['path'])
ModuleNotFoundError: No module named 'bot_extensions.dev'
record_object["vote_count"]
Could i see the code of util.py on line 94, that whole function.
Oh misread.
That's from the library I think
just to clarify, we solved one problem: they were reading the wrong directory
It might be that I just wrote a very lazy dummy class?
probably needs to be ```py
bot.load_extension(f"bot_main.bot_extensions.{filename[:-3]}")
bot_extensions.dev this path makes no sense.
I think if other people ever looking trough this bot is going to have a really hard time.. lol
yes, because before they thought they were in that directory
Lol, pretty much
I'm already rewriting it because it was a messy spaghetti
a good way to sanely handle extensions directory is to do something like ```py
EXTENSIONS_DIR = f"{os.path.join(os.path.dirname(file))}/../{EXTENSIONS_DIR_NAME}"
that way it won't care where you're executing the code from
or just keep it relative and avoid all this mess lol
cause holy shit
btw, thanks for being so patient with me and helping me figure out what's wrong with it
really appreciate it
It's easier to get started in python but it's harder than java if you want to do it perfectly.
can you try one last thing?
Sure, not like I have many options
for filename in os.listdir('./bot_main/bot_extensions'):
if filename.endswith('.py'):
bot.load_extension(f"bot_main.bot_extensions.{filename[:-3]}")
print('{} foi carregado!'.format(filename))
else:
pass
I'm just curious if it will work
I also think i fixed Sasuke's problem i think lol he has been real quite
I don't really get the else: pass but okay
I'm copying their original code
Traceback (most recent call last):
File "/home/bruno/Documents/GitHub/Braver_Bot/bot_main/main.py", line 19, in <module>
bot.load_extension(f"bot_main.bot_extensions.{filename[:-3]}")
File "/usr/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 674, in load_extension
spec = importlib.util.find_spec(name)
File "/usr/lib/python3.9/importlib/util.py", line 94, in find_spec
parent = import(parent_name, fromlist=['path'])
ModuleNotFoundError: No module named 'bot_main'
yep, it isn't even reaching the file
stuck at bot_main

I got other files on the bot_extensions that were apparently giving an error, although it should've ignored them
so I just added a else: pass and it stopped bothering me
probably isn't even the correct use for it, but it stopped giving errors so say what
Shouldn't it not have done anything anyway if it didn't have .py extension
What were they?
This is why i just overengineered my loading cogs part once and never looked at it again.
just a readme
What did you do?
I'll prob try the same path
Recursive importing
Elaborate
!d pkgutil.walk_packages
pkgutil.walk_packages(path=None, prefix='', onerror=None)```
Yields [`ModuleInfo`](https://docs.python.org/3/library/pkgutil.html#pkgutil.ModuleInfo "pkgutil.ModuleInfo") for all modules recursively on *path*, or, if *path* is `None`, all accessible modules.
*path* should be either `None` or a list of paths to look for modules in.
*prefix* is a string to output on the front of every module name on output.
Note that this function must import all *packages* (*not* all modules!) on the given *path*, in order to access the `__path__` attribute to find submodules.
*onerror* is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no *onerror* function is supplied, [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError "ImportError")s are caught and ignored, while all other exceptions are propagated, terminating the search.
Examples:
No need to spoon-feed me the code, just tell me what you did and I'll try on my own
thx
importlib.import_module(name, package=None)```
Import a module. The *name* argument specifies what module to import in absolute or relative terms (e.g. either `pkg.mod` or `..mod`). If the name is specified in relative terms, then the *package* argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. `import_module('..mod', 'pkg.subpkg')` will import `pkg.mod`).
The [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module") function acts as a simplifying wrapper around [`importlib.__import__()`](https://docs.python.org/3/library/importlib.html#importlib.__import__ "importlib.__import__"). This means all semantics of the function are derived from [`importlib.__import__()`](https://docs.python.org/3/library/importlib.html#importlib.__import__ "importlib.__import__"). The most important difference between these two functions is that [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module") returns the specified package or module (e.g. `pkg.mod`), while [`__import__()`](https://docs.python.org/3/library/functions.html#import__ "__import__") returns the top-level package or module (e.g. `pkg`).
inspect.isfunction(object)```
Return `True` if the object is a Python function, which includes functions created by a [lambda](https://docs.python.org/3/glossary.html#term-lambda) expression.
You can check it out but i don't recommend it for beginners.
So I am trying to make a message send once every hour. I came up with this
@client.loop(hour=1)
async def water():
fghj = client.get_Channel(527876598834135047)
await fghj.send('Drink water guys!')
My friend had told me about @tasks.loop() but it didnt work. @client.loop() is honestly just a guess that in no way I expected to work
Well he is right, did you look at the docs?
He had sent me them, but I was going to read them a bit later and just attempt what he had told me. He verified that
@tasks.loop(hour=1)
async def thing():
#code
should work, but it didnt
Well, long night for me I guess
- Did you look at the docs?
- Have you read the docs?
- I have no idea what doesn't work
Only way to learn how to swim is getting wet anyways
Get your sleep 
@lofty mulch youre pretty close to getting it working. I wouldn't stress refactoring everything over some minor import errors
Shit's been persisting for over a week
I have to agree, learn some more now then later do a rework.
How I make my bot online 24/7 with vsc?
I'm really willing to take the long road in an effort to avoid ever having to look at this again
why i got error :
ValueError: could not convert string to float: '10s'
An vps.
Well i have never seen an 's' float
how exactly any yt video ?
you really should understand how relative imports work if you don't already. I think that is hanging you up a little bit
ie what . and .. means
.. is going back a dir, iirc
No videos, pure reading and research. There are a lot of VPS providers out there.
um so what is the true one?
Indeed.
I used it to retrieve some files in another project
. means root dir (where the file is being executed from)
i recommend u heroku, it not complicated and tons of docs
I just can't seem to understand what's wrong with this code
Like, there's nothing obvious
Heroku is not recommend for Discord bots as Heroku is used for web development not Discord bots.
So, might just take the long route and spare myself any problems on the future
As a beginner i recommend putting the main executed file inside your root dir. Later you can get fancy.
So I am setting this command up
@tasks.loop(seconds=5)
async def water():
fghj = client.get_channel(527876598834135047)
await fghj.send('Drink water guys!')
water.start()
but its yelling at me saying: AttributeError: 'NoneType' object has no attribute 'send' when it looks like everything is right, but I could be wrong
A few of your objects in a task are NoneType? Your bot is starting that loop before it's ready. To ensure it waits until it's logged in and the cache is ready, use a before_loop to wait until that time.
@tasks.loop(minutes=10)
async def some_task():
# Do some stuff that uses the cache, like get_user
@some_task.before_loop
async def before_some_task():
await bot.wait_until_ready()
so i need a counter
for a strike
so a strike list
etc have no clue were to start never done somthing like this
:o alright thank you!
Is it possible to cancel an await asyncio.sleep(time) by like returning the function within it?
I don't think so
Dang.
What u need to do?
I want to the bot to cancel a program after a certain amount of time.
timeout
Read the above messages @slate swan
canceling the future may do prolly then
Heh?
can you be more specific? cancel what?
create thread
from threading import Thread
make a sleep quit function
start the thread
it'll sleep and then after times passed in the threat it'll quit()
the bot will turn off with that
Okay thanks, I will look into that!
have you looked at the docs?
yes but i still cant do it
have you tried something?
yes
show code then
well actually, no
Here's an example of mine:
@client.command()
async def startbot(msg):
# IMPORTANT NOTICE: The channel has to be named, "report" (CASE SENSITIVE) in order for the !startbot command to work. Otherwise, it would produce a message saying that it only works in the report channel.
role = await msg.guild.create_role(name='InReports', reason='DO NOT DELETE! Used to limit the user to handle two reports at the same time.')```
!startbot command?
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
discord.Color.blue() should work
I found it a bit difficult and annoying to change colors in discord.py (embed color for instance). I made a class for the different color codes to use in discord.py which can be imported into the m...
ok this is going to sound really dumb
but i need a counter added to a command
but i never have done somthing like this before
@commands.has_permissions(administrator=True)
async def strike(ctx, member: discord.Member, *, reason):
await ctx.send(f"{member.mention} has been striked for {reason}. ")```
i need it to tell me when the number that the member has
after using the command
so like if i use the command on a guy it will tell me one if i have used it once on him
probably want a dictionary with user ID's as the key and the number of strikes as the value
of course, this will reset when the bot resets, so you can consider saving it to a file (bad) or a database (good)
I'm a little confused by this solution (sorry, I've never learned Threads before.)
@ornate glade I asked to explain a bit more. I don't recommend you use threads unless absolutely necessary
ok ill show you
you can't use Threads with asyncio anyway
i have never used a data base before etc so this is somthing i need to learn
good attitude
thanku
oh?
threading*
from threading import Thread
import time
def timer():
time.sleep(230)
quit()
timer()
print("hello world")
it will print hello world at start instead of sleeping 230 seconds
wdym
why cant you use it with asyncio?
either way, I doubt they need threads here
got a problem before, seems they combined asyncio with threading module
discord.py uses threads internally for shard heartbeating
Ah okay. So the bot waits for a reaction by the user. If the time limit from await asyncio.sleep() is reached the bot stops waiting for the reaction and sends to the user "You didn't reply in time!" However, if the user does react, the await asyncio.sleep() is canceled and asks the user a series of questions. Canceling the await asyncio.sleep() is what I am having trouble with.
the role create still doesnt work
await discord.guild.create_role(name=role_name,colour="0x2ecc71",mentionable=True, reason=input_reason)
have you looked into bot.wait_for?
it takes in a timeout argument
how do I make bot create roel
Yes I have used that before, but I wasn't aware that it can wait for reactions as well.
it sure can
Ooooh cool, thanks!
async def makerole(ctx):
await discord.guild.create_role(name=input_role,colour=input_color,mentionable=input_mention, reason=input_reason)
its not working
ctx.guild.create_role
You're looking for the guild to where the message was sent and then creating a role in there.
it seems you don't understand how discord commands work, which is what you're making
I want to execute role creation inside of the code instead of command so what do I do
I want to create the role inside of the console
Pretty sure that's not a thing?
I don't even know what he means. why not just create the role in discord at that point?
🤷
it is a thing
Is there a specific reason on creating the role in the console?
I want to automate creating roles
I want someone to help me make a special verification system for my bot is someone available?
I still don't understanding what you mean by automating? Can you elaborate Sponich?
I just want to make roles without typing a command or doing it manually with discord.py.
using py act = member.activity.type.replace("ActivityType.playing", "Playing").replace("ActivityType.listening", "Listening").replace("ActivityType.watching", "Watching").replace("ActivityType.streaming", "Streaming").replace("ActivityType.competing", "Competing") and ```py
if guild.get_member(member.id) is not None:
acts = member.activities
act = [i for i in acts if isinstance(i, discord.CustomActivity)]
if act:
act = act[0]
if member.activity is None:
act = [i for i in acts if isinstance(i, discord.CustomActivity)]
if act:
act = act[0]
if not act:
act = 'None'```, how can i check if a member of the server has a status? and if theyre not a member of the server, then to ignore the whole status definitive all together and define it as "None"
the first code block works, and so does the second. they both do what theyre meant to do
but i need the custom status to be displayed if the rich presence is none
Yes?
But making the role using a console is technically just using a command. I'm sorry, I'm still very confused by what you're trying to do, can you show some code so I can try to understand it?
so when I input something into the console, the bot will make the role
Why do that in the console though when you can do it on discord?
.
I wanna automate it
Am i able to make this kind of verification for my bot?
here is some code
If yes can someone help me
Also, as I said before, I don't think that's a thing? I see you're trying to using input() functions for the console input, but I don't think that can be used for Discord py.
def new_role(ctx):
discord.guild.create_role(name="new role")
will this work
ignore indentation
oops i forgot to remove ctx
How are you calling on the function new_role()
If you remove the ctx, it will not work.
you need to await it , also discord.guild is the class but you need to use an instance of it
you cannot create the role outside async , discord.py is based on asyncio
just change it to an async function simple
how
async def on_member_join(member):
guild = client.get_guild(730651046459998218)
channel = guild.get_channel(904279966693355550)
myEmbed = discord.Embed(title = f"Welcome",
description= f"You are member {guild.member_count}, \n Enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)", color=0x0ff00)
myEmbed.set_image(url=f"{member.avatar_url}")
await channel.send(embed=myEmbed)
role = discord.utils.get(member.server.roles, id="Unverified")
await client.add_roles(member, role)```
This code is not working i am wanting the bot to give the Unverified role but it aint working and its not giving any errors when i run the code
Sponich you can do:
async def new_role(ctx):
ctx.guild.create_role(name='new role')
And to call on it, you can do await new_role(ctx parameter) to call on it again. However, this has to be within a asynchronous function as well.
i think I found a way
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
async def foo():
# do something```
call it by : `await foo()`
discord.Guild.create_role is a coroutine, you have to await it
I did
.
async def new_role():
await discord.guild.create_role(name="new role")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
read this , it needs to be a guild instance and not just discord.Guild
discord.guild?
huh
discord.Guild is the class... You want the instance of it
how?
i.e message.guld, ctx.guild
you can get it , by using bot.get_guild or any related objects
I added ctx argument in the function and put ctx.guild.create_role
will that work
yea sure
hey, if i have a command like asycn def test(ctx,user:discord.Member), so if i give a wrong argument eg: abc for user, since member abc is not there it will give error.
so is there a way to get that argument(here abc) in @test.error
It would only work if you already have a Context object beforehand and pass it, otherwise decorate the function new_role with commands.Bot.command
yes the args are part of the exception I believe
so how can i get it ?
it isnt working
async def new_role(ctx):
await ctx.guild.create_role(name="new role")
https://paste.pythondiscord.com/rihebiyedo.py Its not working
oh thank u
what do I have to put for ctx??

its missing the ctx argument when I put new_role()
where do you call the new_role function?
!d discord.ext.commands.Bot.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
like right after
pass a context object to it
do I put @client.command() before the function
Yes.. you decorate the function
ok so that was a command , i thought they were trying to make a helper function for some commands lol
RuntimeWarning: coroutine 'Command.call' was never awaited
bruh im getting this
and thisRuntimeWarning: Enable tracemalloc to get the object allocation traceback
Show your code
You are probably calling new_role when you aren't supposed to
Since you decorated the function and turned it into a Command object you can just send a message on discord with your command prefix and new_role to run the command's callback
wait second
hey guys!
question if i were trying to create a party system that grouped discord users together, could i use a class to make it happen?
I'm new to classes and I'm wondering if I should continue to learn about them so I can make this work
How do I unban a user with discord tags or IDs
I don't think classes would be useful here really, or at the very base of it
I would use Queues instead
!d asyncio.Queue
class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.
If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.get "asyncio.Queue.get").
Unlike the standard library threading [`queue`](https://docs.python.org/3/library/queue.html#module-queue "queue: A synchronized queue class."), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.qsize "asyncio.Queue.qsize") method.
This class is [not thread safe](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading).
And you can use this in conjunction with asyncio.wait_for
What I was originally trying was just creating dictionaries in my JSON file and then listing the parties and their users in there
But I was having a hard time doing things like checking whether or not the user was already in a party etc.
Is the party data supposed to persist?
Until the party is disbanded
Which would be run by a command that would remove the party from the dictionary
Yea, but you said it will stay until the party is disbaned
Meaning it won't persist if the bot goes offline and online
Oh
Well in this case I've been leaving the bot online
It's a small project I'm working on
So that's not an issue
Perhaps its a good idea to get a database setup for this
You can do stuff like fetch and see if its None etc, at least with pg
Yeah, I've heard that, but I'm just working with JSON right now
I would have to rewrite everything I've written to work with a database
Using JSON here doesn't seem very effective to me, but you can do what you want to do/can do
I mean it's working so far...
Other than that you just need to access to dict from the json data and check if its in values() to check if their in a party
Working so far, doesn't mean working well
It's working the way I want it to.
It's a text based game, so data can be stored in JSON.
I can have a cup with a small hole and it would be constantly losing water, but for a few seconds it can still hold water
I'll keep working
i have a question
what is tag?
bye
excuse me
Hi
so i wanted to use json for my discord bot for my server but someone said it doesn't have dependency injection, is this true?
it worked ,ty
Oh Nova, hi
Oh hey @pulsar shell
I'm not that advanced into coding yet, so i'm not sure if i can answer ur question
hm
json is not a database
.
what do you want
Obviously, but it would be better to ask there since nobody is replying to them.
??
Where's the decorator
Why do you need a decorator
It isn't a command
Just a normal function
Then show the command which is running it
I think it's solved, it was an hour ago
Oh, didn't see
Sure, what is it
# CREATING THE PARTY
async def create_party():
print(str(ctx.author))
if str(ctx.author) in data["parties"]["usersinparties"]:
await ctx.reply("You are already in a party!")
else:
data["parties"]["usersinparties"] = [(str(ctx.author)), (str(user))]
data["parties"][str(partyid)] = [(str(ctx.author)), (str(user))]
members.append(str(ctx.author))
members.append(str(user))
await ctx.send(f"Party created!\nMembers: {members}")
with open("users.json", "w") as f:
json.dump(data, f, indent=4)
So I have this code here, right
yes
ctx is undefined?
{
"users": {
"326903703422500866": {
"user": "Kazido#0139",
"coins": 0,
"class": "none",
"experience": 0,
"inventory": []
}
},
"parties": {
"usersinparties": [
"Kazido#0139",
"monkes#9457"
],
"LbxGwpuTbM": [
"Kazido#0139",
"monkes#9457"
]
}
}
And I have this JSON file
yes
No, this is a snippet of a larger part of code
There is a check to make sure the user who is running the party command is not in ["usersinparties"]
Which is nested inside of the ["parties"] dictionary
However, it is failing to pass the check. If you look in the JSON file, "Kazido#0139" is in the ["usersinparties"] list, but the code isn't going to the await ctx.reply("You are already in a party!") line..
because the ctx.author is inside yet another json "LbxGwpuTbM"
No, it's passing the check...
so it would be ["LbxGwpuTbM"]["parties"]["usersinparties"]
ok nvm there are 2 of them
? But ["LbxGwpuTbM"] is outside of the location that I'm trying to check?
yea
yeah...
that list is the actual party, but that is fine.
I have the ["usersinparties"] list just as a master list of everyone who is currently in a party, so that if they try to make another one it won't let them.
I'm not very experienced with json reading/writing but I'm guessing you have opened the file before doing the check already? (I'm not sure if you even need to do that lol)
# CREATING THE PARTY
async def create_party():
with open("users.json", "r") as f:
data = json.load(f)
print(str(ctx.author))
if str(ctx.author) in data["parties"]["usersinparties"]:
await ctx.reply("You are already in a party!")
else:
data["parties"]["usersinparties"] = [(str(ctx.author)), (str(user))]
data["parties"][str(partyid)] = [(str(ctx.author)), (str(user))]
members.append(str(ctx.author))
members.append(str(user))
await ctx.send(f"Party created!\nMembers: {members}")
with open("users.json", "w") as f:
json.dump(data, f, indent=4)
I added ```py
with open("users.json", "r") as f:
data = json.load(f)
yeah ig
Still running into the same issue unfortunately
why do you tend to save user tags and not ids tho?
np, thansk for trying
It's just simpler for me to see in the JSON file who is in a party and whatnot for the debugging process
I could use ID's but for the sake of having a clean dictionary that displays the users in the party, it's nice to have the tags.
{
"users": {
"326903703422500866": {
"user": "Kazido#0139",
"coins": 0,
"class": "none",
"experience": 0,
"inventory": []
}
},
Put both
I did use ID here and the tag in the account part of the JSON
So I could just do that again..
"parties": {
"usersinparties": [
"Kazido#0139 : 326903703422500866",
"monkes#9457 : 730955069201317999"
],
"tESLUYqvaZ": [
"Kazido#0139 : 326903703422500866",
"monkes#9457 : 730955069201317999"
]
}
There u go ❤️
Also how can i shorten this up
[(str(ctx.author)) + ' : ' + (str(ctx.author.id)), (str(user)) + ' : ' + (str(user.id))]
I mean you could probably fix this easily if you did some simple debugging. Have you questioned if you're indexing right. Having you tried printing that data[][] bs and seeing if it’s returning the list of strings like you want it to.
Also json isn’t meant to be used like this. Consider a database. SQLite is good for lightweight data interactions like this.
I guess I have just been looking at the JSON. I'll try printing them.
Yeah, you are the 10th person to have told me that. I'm just doing basic stuff, and I'd have to rewrite my entire code to change it to a database.
it’s worth it.
It only gets worse and worse down the road
Where it will make more of a significant difference
How would I even start to learn it..
And are databases files that are just stored on my PC?
Also this may be all nice and all but there’s a flaw in this. Discord usernames and discriminators aren’t unique. Meaning someone could copy your username and discriminator(if they had nitro) and throw off any type of logical operations that use those two for checking stuff like this. The only thing that’s unique about a user is there ID.
haha this guy still stuck mixing shit until its muffin
???????
Okay, so how would I get started with a database?
just me or discord doesn't show when Myxi is typing
Might as well say fuck it and rewrite everything I've started xD
You know SQL?
Nope
I would get started there.
It’s not as bad as people make it out to be.
You can be writing basics in like 30 minutes to an hour. The syntax isn’t hard to follow and everything in the learning process tends to go smooth.
SQL shouldn't be hard, it's basic English to an extent
you know a programming language that’s basically English. Cobol
because you have never used an actual db before, i would suggest to go with the built-in sqlite3 module to get started. this is not asynchronous so you have to start a basic offline project to learn everything then you may use some async ones by searching for them
!d sqlite3
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
confusion
lmao
maybe this
So in my code, would I only have to change the JSON writing stuff?
Also how would I test the code if it all has to do with discord bots and users?
Just write sample code and test it in offline?
is there a way to get current position of a song in ffmpeg?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
😥
hmm
if guild.banner is None:
pass
else:
banner = guild.banner.replace(size=2048)
success_embed.set_image(
url=banner.url
)
```in an embed if i wanna make the image bigger what do i do
i ran the command and the image is still so small
check the url if its really of that size or not
it isnt thats why im making the size 2048
discord.Guild.banner returns discord.Asset
which has a method with_size
!d discord.Asset.with_size
with_size(size, /)```
Returns a new asset with the specified size.
it will return a new object and then you may get the url by discord.Asset.url
have you installed discord?
have u installed it
In the cmd prompt
pip install discord
@opaque sun
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
hm
where can i find rate limit documentation for every route in discords api? ect. get_channel rate limit
and also is there a way to get the current position of what you are playing in ffmpeg? ect. a mp3 file named test.mp3
who said it has anything to do with that?
no
they purposely leave it ambiguous
what does that mean?
so everyone doesn’t go and push the limits to their max
they dont show each ratelimit
btw get_channel doesnt hit an api, it hits cache
oh ok
fetch_channel hits the api
does get_channel freeze async because its not async function?
no
because its searching cache
its not hitting an asynchronous api
ok
what is the rate limit on fetch_channel?
they didnt specify it https://discord.com/developers/docs/topics/rate-limits iirc
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
well
time to see what the rate limit is myself 
as I said, they leave the rate limits ambiguous so people dont just abuse the api
what does that mean
he literally told you, they dont tell you the ratelimits so people don't abuse the api
so it does have a rate limti only no one knows it?
Ratelimits are dynamic anyways, so even if they told you, they change all the time so you cant have a fixed value for them
what is needed for pass_context = True and pass_context = False?
|| as your bot expands server-wise you can make more calls.
pass_context is deprecated
what was he needed for?
If they didnt there would be no way to properly handle them
pass_context (at least I assume) is used to make ctx an optional parameter
Thanks
how can i from discord.app import Option
what is discord bot whitelabel ?
what?
is this graded?
No it’s revision for the exam
a guy is asking he wants my bot as whitelabeled.
But it’s damn hard
like customize it, change name , logo
Can I dm u?
i am clueless
nope
he does not know what he is talking bout
easy shit
firstly, its not related to discord bots
yes
second, its so easy wdym.....
dont dm me
is it possible to change name n logo of the bot in a particular server ?
@hybrid ruin this is your exam not mine, you gotta do it yourself
you can change nickname , but not usernames and logo for now
It’s not an exam
then homework*
scaterx, what part of the problem do you not understand?
Python is a powerful general-purpose programming language. Our Python tutorial will guide you to learn Python one step at a time with the help of examples.
also , this channel is not related to that stuff
Well I can’t find the help channel bro
ok thx.
Guys can we make a bot from python that sends tweets from discord to twitter?
For example if we write /tweet and the tweet, this should post it to my twitter account. Is this possible ?
Checkout Twitter API but most prolly it's not possible
Wdym??
Oh ok
You can use other dumb ways tho
Like?
that guy wants my code lmao
Creating a code which can control your PC
And send tweets like that yk
🙂
anyone wanna make an anti nuke
😃
with?
BTW @primal scarab it's possible using the API
https://vhudyma-blog.eu/post-a-tweet-using-twitter-api/#:~:text=First%2C log in to the,-> "Create App".
i cant see
Ohk thank you :)
no
that maybe why
i tried installing
how do i make a slash command in a cog?
but error
because the code needs to install the packages when you run the script
like .json
wdym error
what does it say
why
Until you are using any 3rd party lib
how use him
Wdym?
what
just get a plugin
which?
make a lib folder
Any plug in you like
idkkk
.
Good morning
what type of bot are you making
you can with some weird extension thing
yea but like anti nuker music etc
I said that
Yes
mk
Don’t spoon feed
wdym
Tell him exactly how to code
he knows how to code
thats not what he needs help with
u cant use slash commands in dpy
You can with an extension
discord bot
Here
yea but he doesnt have a lib
Then install it
yes
hey guys, is there a way to get the id of the person you're replying to
What IDE is he using?
told him that
what?
Wdym
idk ask him
ctx.author.id
ctx.author.id
pls link video of python discord.py and termux pls
Wrong person
but wouldn't that return my id?
well yeah?
I want the id of the person whose message I'm replying to
does anyone want to make a anti nuke bot