#discord-bots

1 messages · Page 616 of 1

slate swan
#

so would i have to do d.get(playing) for example?

sullen shoal
#

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

slate swan
#

How do i check if a user is the guild owner ?
i don't wanna do ```py
@commands.has_permissions(administrator=True)

sullen shoal
#

!d discord.Guild.owner

unkempt canyonBOT
#

property owner: Optional[discord.member.Member]```
The member that owns the guild.
slate swan
#

how do i make the bot go offline without closing vs code?

sullen shoal
#

close the process of python

slate swan
#

how?

sullen shoal
#

ctrl + c press that while focusing the terminal window

#

otherwise you have to open the task manager and search for a process named python

tawdry perch
#

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}")

slate swan
#

Is the bot in the server where the emoji is located?

tawdry perch
#

So yes

slate swan
sullen shoal
#

global variables :/

#

await ctx.send("It is <@" + str(player1.id) + ">'s turn.")
consider using f-strings and discord.Member.mention

#

!tags fstring

slate swan
#

Okay, What do i have to change in global variables then?

unkempt canyonBOT
#
Did you mean ...

sql-fstring
f-strings

sullen shoal
#

you shouldnt need global variables at all. you have it inside a class. set them as attributes of the class

slate swan
#

Okay I will try.

sullen shoal
#

also follow the pep8 style guide

slate swan
#

I will update(cry for help) you if I fail

sullen shoal
#

instead of thisCasing use this_casing

#

snake case

river kindle
#

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} ')```
slate swan
#
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

velvet tinsel
#

Wdym?

river kindle
#

nonono

#

is the transaltor who makes spaces

#

not me

sage otter
quaint epoch
#

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

velvet tinsel
#

What do you need?

quaint epoch
velvet tinsel
#

Well it should have no problem with \n

slate swan
velvet tinsel
#

!e

product = ‘test’
stars = 5
message = ‘ok’
embed = discord.Embed (
        title = f 'Product Review',
        description = f'Prodotto: {product} \ n Stars: {stars} \ n Rating: {message} ')
unkempt canyonBOT
#

@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)
velvet tinsel
#

!e

product = ‘test’
stars = 5
message = ‘ok’
embed = discord.Embed (
        title = f 'Product Review',
        description = f'Prodotto: {product} \ n Stars: {stars} \ n Rating: {message} ')
unkempt canyonBOT
#

@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)
velvet tinsel
#

Wth is wrong

leaden jasper
#

how to make a string a discord.PartialEmoji

leaden jasper
velvet tinsel
#

Oh

slate swan
velvet tinsel
#

I’m in

jagged root
#

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.

leaden jasper
unkempt canyonBOT
leaden jasper
#

but idk how to if its in a category

jagged root
#

How should i start? no idea

leaden jasper
#

umm

jagged root
#

just an example so i can make an idea if you want

leaden jasper
#

depends what ur thing does

#

like is it a command

jagged root
#

on listen

#

detects any word and answers

junior verge
#

How would you make a command that would be like !invite 1 that you would get a 1 use invite link?

slate swan
#

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)```
jagged root
slate swan
leaden jasper
jagged root
#

np

velvet tinsel
leaden jasper
velvet tinsel
#

O k

slate swan
velvet tinsel
slate swan
#

Thanks dud

velvet tinsel
#

Thanks to Sherlock for introducing this to me ^_^

slate swan
#

^o^

velvet tinsel
#

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

slate swan
#

yes I saw that..

velvet tinsel
#

@slate swan I’m not an expert, I’m using my own experiences. Can you please confirm?

slate swan
#

Also does it have to be in a seperate cogs file? Or can I paste it in my main.py aswell

velvet tinsel
#

?

#

I dont think you need cogs

slate swan
#

i tried also lol

velvet tinsel
#

Didnt we all

slate swan
#

lol

velvet tinsel
#

😂

slate swan
#

although for webhooks i have got away with except Exception:

#

but when i tried to do specific error handling it didnt work

velvet tinsel
#

Where did you learn python?

#

Just wondering

slate swan
#

taught myself

velvet tinsel
#

Book? Tutorial?

slate swan
#

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

velvet tinsel
#

Oh I learnt off a book

#

Once I had the basics i moved on

slate swan
#

but nothing structured

velvet tinsel
#

Oh

#

😛 happens to the best of us

slate swan
#

i like python coz its pretty easy to figure out

velvet tinsel
#

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

slate swan
#

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 ?

velvet tinsel
#

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

velvet tinsel
slate swan
velvet tinsel
#

Oh

#

I cannot understand that entire thing

#

Looks all C++ to me

slate swan
#

u can do len(data)

#

so like x = len(data), and then change rand.int to 0,x

velvet tinsel
#

Thinking about it that seemed like the most obvious thing

slate swan
#

actually u need to do len(j['data']['children'])

#

i tried to print len(data) and i got 109

#

actually im confused

velvet tinsel
#

[‘data’][‘children’]

#

Try that one

velvet tinsel
slate swan
#

it was the rand.int inside the dictonary parsing but it does make sense what i said lol

velvet tinsel
#

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

slate swan
#

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

velvet tinsel
#

Yes

slate swan
#

Lol

velvet tinsel
#

Right going to sleep bye

lofty cedar
#

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...'

unkempt canyonBOT
#

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.")
full lily
#

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":

lofty cedar
#

and that should stop my elifs from being skipped?

full lily
#

your if condition is always true, the way you have it now

lofty cedar
#

because it works when in solo code, but not when in a discord bot

full lily
#

so the elif is never even evaluated

lofty cedar
#

Why is it always true?

full lily
#

The first part of this condition is fine
if dino == "apa":

#

The second part always evaluates to True

#

!e
print(bool("apato"))

unkempt canyonBOT
#

@full lily :white_check_mark: Your eval job has completed with return code 0.

True
full lily
#

@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

lofty cedar
#

ohhhhhh

#

so im basically saying, if its apa or if apato = true, do xyz

slate swan
#

aslo how do i hide my bot token on repl.it?

slate swan
#

By using a .env file

#

How can I check if a button is pressed by the custom_ID of that component?

dusk dust
#

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'
slate swan
#

{ctx.command}

dusk dust
#

ok

dusk dust
dusk dust
#

is the same

slate swan
#

Send me the

@bot.command()
async def ...```
dusk dust
#

@bot.event
async def on_command_error(ctx, error):

flint cosmos
#

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()
slate swan
#

Why don't you do it via a seperate channel that only you can see?

flint cosmos
slate swan
#

ok lol

jade tartan
#

Is there any one that could help make a verification system?

slate swan
#

is there a function to return the user/members current channel id?

old gate
#

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

unkempt canyonBOT
#

@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!

old gate
#

oops

slate swan
#

all i did was remove the *

#

and it still works with the *

old gate
#

what does that do i just want to put the users id in there so it send him the message only

slate swan
old gate
#

Trying to only send dm's to one person

slate swan
old gate
#

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

slate swan
# old gate yep

this worked for me, i just changed the name of the command name

old gate
#

woah

slate swan
old gate
#

Nope

slate swan
old gate
#

a bunch

slate swan
old gate
slate swan
# old gate

can i see the message you are trying to send/?

old gate
#

i'll just stick with the hard way

#

i hate python

tulip panther
#
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?

old gate
#

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

dapper cobalt
#

I'm unsure if this is advertising or not. But, just in case - @hot cobalt

brittle ingot
#

quite odd

slate swan
dapper cobalt
slate swan
#

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

slate swan
blissful lagoon
#

@old gate please don't advertise on our server

blissful lagoon
slate swan
slate swan
old gate
#

Sorry about that

old gate
#

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

slate swan
old gate
#

@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
#

@slate swan allot of exceptions in docs btw dont use bare exceptions as they raise for any error

old gate
#

what do i change inside that protion where i put his user id

slate swan
#

But nevermind cuz your using user

#

@old gate do you always one to send it to the same member?

old gate
#

yep

old gate
#

Also sorry i wasnt trying to advertise its just confusing

slate swan
kindred epoch
#
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?
old gate
#

ok i'll try it @slate swan ty

slate swan
old gate
#

May i add you as a friend?

slate swan
old gate
#

Thats ok thats why i asked first thanks

slate swan
#

@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

old gate
#

🙂 ty

slate swan
slate swan
brittle ingot
#

for webhook?

slate swan
#

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

slate swan
#

I wanted to detect if someone deleted the webhook

slate swan
#

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

brittle ingot
#

Did you check the Discord API docs? They may have the specifics codes that go with certain issues like for instance a deleted webhook

slate swan
#

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

lofty mulch
#
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

brittle ingot
#

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.

lofty mulch
#

and __Dev_Tools__ is my extension

kindred epoch
#
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?

pale zenith
#

cardcoin or votecoin are integers

#

1234[0] isnt a thing

kindred epoch
#

<Record vote_count=39> that is what it returns tho

primal fox
lofty mulch
#

It reads the file, but doesn't want to load in

primal fox
#

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?

slate swan
lofty mulch
#

I do

primal fox
#

what's your new error then?

lofty mulch
#

still the same error

slate swan
#

does it have ```py
bot.add_cog(CogClass)

primal fox
#

ModuleNotFoundError: No module named '__Dev_Tools__' means it can't find the file @lofty mulch

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'

primal fox
#

might help to show your updated code

#

again, that error means the file isn't found

lofty mulch
#
# 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

primal fox
#

the loading code

lofty mulch
#
 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```
primal fox
#

so you've been given 2 suggestions already: trim .py from the filename and add bot_extensions in front of your filename

lofty mulch
#

Oooh, you asked me to rename it?

#

Sorry, totally flew over my head

#

Lemme do it

primal fox
#
 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
lofty mulch
#

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

quaint epoch
#

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?

lofty mulch
#

of the file*

primal fox
#

@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.

lofty mulch
#

so, rename it to dev.tools

cerulean osprey
#

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?

primal fox
primal fox
cerulean osprey
#

Yeah so why didnt they display the same thing?

primal fox
#

can you show the original code before you fixed it?

cerulean osprey
#

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}')
lofty mulch
#

Reopening Vscode

primal fox
#

do you have name = ... outside of this function, as a global variable? maybe it's reading that

cerulean osprey
#

No, I was reffering to it inside of client..change_presence() so maybe thats why?

lofty mulch
#

Here's my file tree

primal fox
#

it's like you're making a new dog object like

dog = Dog(name="Fido")
lofty mulch
#

Fido is a pretty cute name tbh

cerulean osprey
#

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?

magic ore
magic ore
#

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')`
cerulean osprey
#

There’s nothing that references either of those outside of the stuff I sent tho

kindred epoch
#
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?

primal fox
#

aka I have no idea

lofty mulch
#

ffs

#

now it doesn't recognize the path

cerulean osprey
lofty mulch
#

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'```
kindred epoch
#

Tbh now just add the file names in a list and load them

primal fox
#

ah

lofty mulch
#

I swear, I have a harder time trying to connect the cogs rather than actually coding

lofty mulch
kindred epoch
#

Add them in the same folder the main bot file is in

primal fox
lofty mulch
#

What should I do instead?

primal fox
#

the ./bot_extensions is probably correct

cerulean osprey
lofty mulch
#

Gave the same error, though. That's why I tried the path=

primal fox
lofty mulch
#

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

cloud dawn
lofty mulch
#

Like, to execute the file?

cloud dawn
#

Yes.

lofty mulch
#

Nope

#

I'm using VSCode's F5

cloud dawn
#

Could you print the cwd?

lofty mulch
#

Lemme see If I can

primal fox
#

yeah, you need to be running this from within your bot directory

#

the . is a relative import

kindred epoch
unkempt canyonBOT
#

@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
cloud dawn
#

You can't index an int.

lofty mulch
cloud dawn
#

Should look something like print(os.getcwd())

lofty mulch
#

/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

cloud dawn
#

Hmm okay could you do this aswell? print(os.listdir('./'))

lofty mulch
cloud dawn
#

Where is the folder?

#

Is it one higher?

kindred epoch
lofty mulch
#

Right here

#

It's one higher

cloud dawn
lofty mulch
#

snytax error

#

on line 29, although there's no line 29

cloud dawn
#

traceback?

lofty mulch
#

SyntaxError: unexpected EOF while parsing

cloud dawn
cloud dawn
unkempt canyonBOT
#

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.

lofty mulch
#

ah, you want me to raise a exception and print a full traceback?

kindred epoch
# cloud dawn That's because you need to extract that value, that is not done by indexing but ...
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
primal fox
#

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
cloud dawn
#

Well it should throw a traceback by default.

lofty mulch
#

that's all the terminal gave me

#

Weird

cloud dawn
#

I think he already go trough the loading of the cogs but this is an error inside a cog.

lofty mulch
# primal fox try ```py for filename in os.listdir('./bot_main/bot_extensions'): if filen...

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'

lofty mulch
#

It recognizes the file

#

But it simply doesn't work

cloud dawn
lofty mulch
cloud dawn
#

Oh misread.

lofty mulch
#

That's from the library I think

primal fox
#

just to clarify, we solved one problem: they were reading the wrong directory

lofty mulch
#

It might be that I just wrote a very lazy dummy class?

primal fox
#

probably needs to be ```py
bot.load_extension(f"bot_main.bot_extensions.{filename[:-3]}")

cloud dawn
#

I think if other people ever looking trough this bot is going to have a really hard time.. lol

primal fox
#

yes, because before they thought they were in that directory

lofty mulch
#

I'm already rewriting it because it was a messy spaghetti

primal fox
#

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

lofty mulch
#

at this point

#

I think it might be easier to just write in java

cloud dawn
#

or just keep it relative and avoid all this mess lol

lofty mulch
#

cause holy shit

lofty mulch
#

btw, thanks for being so patient with me and helping me figure out what's wrong with it

#

really appreciate it

cloud dawn
#

It's easier to get started in python but it's harder than java if you want to do it perfectly.

primal fox
lofty mulch
#

Sure, not like I have many options

primal fox
#
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

cloud dawn
#

I also think i fixed Sasuke's problem i think lol he has been real quite

cloud dawn
primal fox
lofty mulch
#

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

cloud dawn
lofty mulch
#

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

slate swan
#

Shouldn't it not have done anything anyway if it didn't have .py extension

lofty mulch
#

It shouldn't

#

but it still gave me errors

#

dunno why

slate swan
#

What were they?

cloud dawn
#

This is why i just overengineered my loading cogs part once and never looked at it again.

lofty mulch
#

just a readme

lofty mulch
#

I'll prob try the same path

cloud dawn
#

Recursive importing

lofty mulch
#

Elaborate

cloud dawn
#

!d pkgutil.walk_packages

unkempt canyonBOT
#

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:
lofty mulch
#

No need to spoon-feed me the code, just tell me what you did and I'll try on my own

#

thx

unkempt canyonBOT
#

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.
cloud dawn
#

You can check it out but i don't recommend it for beginners.

cerulean osprey
#

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

cloud dawn
#

Well he is right, did you look at the docs?

cerulean osprey
#

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

lofty mulch
#

Well, long night for me I guess

cloud dawn
#
  1. Did you look at the docs?
  2. Have you read the docs?
  3. I have no idea what doesn't work
lofty mulch
cloud dawn
lofty mulch
#

So might go full in aswell, why not

#

I will eventually, just gotta start planning

primal fox
#

@lofty mulch youre pretty close to getting it working. I wouldn't stress refactoring everything over some minor import errors

lofty mulch
#

Shit's been persisting for over a week

cloud dawn
#

I have to agree, learn some more now then later do a rework.

lyric moat
#

How I make my bot online 24/7 with vsc?

lofty mulch
#

I'm really willing to take the long road in an effort to avoid ever having to look at this again

brave flint
#

why i got error :
ValueError: could not convert string to float: '10s'

cloud dawn
cloud dawn
lyric moat
primal fox
#

ie what . and .. means

lofty mulch
#

.. is going back a dir, iirc

cloud dawn
brave flint
cloud dawn
lofty mulch
#

I used it to retrieve some files in another project

cloud dawn
brave flint
lofty mulch
#

I just can't seem to understand what's wrong with this code

#

Like, there's nothing obvious

cloud dawn
#

Heroku is not recommend for Discord bots as Heroku is used for web development not Discord bots.

lofty mulch
#

So, might just take the long route and spare myself any problems on the future

cloud dawn
cerulean osprey
#

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

magic ore
#

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()
blazing coral
#

so i need a counter

#

for a strike

#

so a strike list

#

etc have no clue were to start never done somthing like this

ornate glade
#

Is it possible to cancel an await asyncio.sleep(time) by like returning the function within it?

maiden fable
#

I don't think so

ornate glade
#

Dang.

maiden fable
#

What u need to do?

ornate glade
#

I want to the bot to cancel a program after a certain amount of time.

slate swan
#

timeout

maiden fable
#

Read the above messages @slate swan

slate swan
#

canceling the future may do prolly then

ornate glade
#

Heh?

primal fox
distant warren
#

How do I create a role with d.py?

distant warren
#

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

ornate glade
#

Okay thanks, I will look into that!

distant warren
#

Now...

primal fox
#

have you looked at the docs?

distant warren
#

yes but i still cant do it

primal fox
distant warren
#

yes

primal fox
#

show code then

distant warren
#

well actually, no

ornate glade
#

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.')```
distant warren
#

!startbot command?

primal fox
#

!d discord.Guild.create_role

unkempt canyonBOT
#

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.
distant warren
#

ty

#

What do I put for color if I wanna make it blue

primal fox
#

discord.Color.blue() should work

distant warren
#

ok

#

what if green

ornate glade
blazing coral
#

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

primal fox
#

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)

ornate glade
primal fox
#

@ornate glade I asked to explain a bit more. I don't recommend you use threads unless absolutely necessary

visual island
#

you can't use Threads with asyncio anyway

blazing coral
blazing coral
#

thanku

vocal plover
visual island
#

threading*

distant warren
#
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

distant warren
vocal plover
primal fox
#

either way, I doubt they need threads here

visual island
#

got a problem before, seems they combined asyncio with threading module

vocal plover
#

discord.py uses threads internally for shard heartbeating

ornate glade
#

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.

distant warren
#

the role create still doesnt work

#
await discord.guild.create_role(name=role_name,colour="0x2ecc71",mentionable=True, reason=input_reason)
primal fox
#

it takes in a timeout argument

distant warren
#

how do I make bot create roel

ornate glade
#

Yes I have used that before, but I wasn't aware that it can wait for reactions as well.

ornate glade
#

Ooooh cool, thanks!

distant warren
#
async def makerole(ctx):
   await discord.guild.create_role(name=input_role,colour=input_color,mentionable=input_mention, reason=input_reason)
#

its not working

ornate glade
#

ctx.guild.create_role

#

You're looking for the guild to where the message was sent and then creating a role in there.

primal fox
distant warren
#

I want to execute role creation inside of the code instead of command so what do I do

primal fox
#

commands take in arguments, so you need to add those in addition to ctx

distant warren
#

How do I do it inside of the console, create roles

#

i dont understnad

distant warren
ornate glade
#

Pretty sure that's not a thing?

primal fox
#

I don't even know what he means. why not just create the role in discord at that point?

ornate glade
#

🤷

distant warren
#

it is a thing

ornate glade
#

Is there a specific reason on creating the role in the console?

distant warren
#

I want to automate creating roles

jade tartan
#

I want someone to help me make a special verification system for my bot is someone available?

ornate glade
#

I still don't understanding what you mean by automating? Can you elaborate Sponich?

distant warren
#

I just want to make roles without typing a command or doing it manually with discord.py.

slate swan
#

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

jade tartan
#

Yes?

ornate glade
distant warren
#

so when I input something into the console, the bot will make the role

ornate glade
#

Why do that in the console though when you can do it on discord?

jade tartan
#

Am i able to make this kind of verification for my bot?

distant warren
#

here is some code

jade tartan
#

If yes can someone help me

ornate glade
#

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.

distant warren
#
def new_role(ctx):
discord.guild.create_role(name="new role")

will this work

#

ignore indentation

#

oops i forgot to remove ctx

ornate glade
#

How are you calling on the function new_role()

#

If you remove the ctx, it will not work.

distant warren
#

wdym

#

let me test it

slate swan
#

you need to await it , also discord.guild is the class but you need to use an instance of it

distant warren
#

its not a async function

#

u cant await if its not async function

slate swan
#

you cannot create the role outside async , discord.py is based on asyncio

#

just change it to an async function simple

distant warren
#

how

jade tartan
#
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
distant warren
#

wait o im stupid

#

i hope this works

ornate glade
# distant warren wdym

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.

distant warren
#

i think I found a way

#

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
pliant gulch
#

discord.Guild.create_role is a coroutine, you have to await it

distant warren
#
async def new_role():
    await discord.guild.create_role(name="new role")

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
#

read this , it needs to be a guild instance and not just discord.Guild

pliant gulch
#

discord.guild?

distant warren
#

huh

pliant gulch
#

discord.Guild is the class... You want the instance of it

distant warren
#

how?

pliant gulch
#

i.e message.guld, ctx.guild

slate swan
#

you can get it , by using bot.get_guild or any related objects

distant warren
#

I added ctx argument in the function and put ctx.guild.create_role

#

will that work

slate swan
#

yea sure

novel bolt
#

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

pliant gulch
#

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

primal fox
novel bolt
distant warren
#

it isnt working

#
async def new_role(ctx):
   await ctx.guild.create_role(name="new role")
jade tartan
novel bolt
#

oh thank u

distant warren
#

what do I have to put for ctx??

distant warren
#

its missing the ctx argument when I put new_role()

slate swan
#

where do you call the new_role function?

pliant gulch
#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@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").
distant warren
#

like right after

slate swan
#

pass a context object to it

distant warren
pliant gulch
#

Yes.. you decorate the function

distant warren
#

ok let me try now

#

ive literally been trying for 4 hours

slate swan
#

ok so that was a command , i thought they were trying to make a helper function for some commands lol

distant warren
#

RuntimeWarning: coroutine 'Command.call' was never awaited
bruh im getting this

#

and thisRuntimeWarning: Enable tracemalloc to get the object allocation traceback

pliant gulch
#

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

distant warren
#

wait second

abstract kindle
#

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

distant warren
#

How do I unban a user with discord tags or IDs

pliant gulch
#

I would use Queues instead

#

!d asyncio.Queue

unkempt canyonBOT
#

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).
pliant gulch
#

And you can use this in conjunction with asyncio.wait_for

abstract kindle
#

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.

pliant gulch
#

Is the party data supposed to persist?

abstract kindle
#

Until the party is disbanded

#

Which would be run by a command that would remove the party from the dictionary

pliant gulch
#

Yea, but you said it will stay until the party is disbaned

#

Meaning it won't persist if the bot goes offline and online

abstract kindle
#

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

pliant gulch
#

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

abstract kindle
#

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

distant warren
#
    await ctx.guild.unban(tag)
#

would that unban you

pliant gulch
#

Using JSON here doesn't seem very effective to me, but you can do what you want to do/can do

abstract kindle
#

I mean it's working so far...

pliant gulch
#

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

pliant gulch
abstract kindle
#

It's working the way I want it to.

#

It's a text based game, so data can be stored in JSON.

pliant gulch
#

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

abstract kindle
#

I'll keep working

pulsar shell
slate swan
distant warren
#

user tag

#

anyways I got it so no need to do it

#

goodbye i gtg

grim oar
#

bye

pulsar shell
#

excuse me

grim oar
#

Hi

pulsar shell
#

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?

novel bolt
quick gust
#

Oh Nova, hi

abstract kindle
#

Oh hey @pulsar shell

#

I'm not that advanced into coding yet, so i'm not sure if i can answer ur question

jade crater
#

hm

slate swan
#

json is not a database

distant warren
#

what do you want

jade crater
distant warren
grim oar
jade crater
#

It isn't a command

#

Just a normal function

grim oar
#

Then show the command which is running it

jade crater
#

I think it's solved, it was an hour ago

grim oar
#

Oh, didn't see

abstract kindle
#

ok

#

I got another question

jade crater
#

Sure, what is it

abstract kindle
#
        # 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

jade crater
#

yes

slate swan
#

ctx is undefined?

abstract kindle
#
{
    "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

jade crater
#

yes

abstract kindle
#

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..

slate swan
#

because the ctx.author is inside yet another json "LbxGwpuTbM"

abstract kindle
#

No, it's passing the check...

slate swan
#

so it would be ["LbxGwpuTbM"]["parties"]["usersinparties"]

#

ok nvm there are 2 of them

abstract kindle
#

? But ["LbxGwpuTbM"] is outside of the location that I'm trying to check?

slate swan
#

yea

abstract kindle
#

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.

quick gust
#

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)

abstract kindle
#
        # 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)

quick gust
#

yeah ig

abstract kindle
#

Still running into the same issue unfortunately

quick gust
#

aw

#

I have 0 clue from this point on, sorry

slate swan
#

why do you tend to save user tags and not ids tho?

abstract kindle
#

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": []
        }
    },
slate swan
#

Put both

abstract kindle
#

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))]
sage otter
#

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.

abstract kindle
#

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.

sage otter
#

it’s worth it.

#

It only gets worse and worse down the road

#

Where it will make more of a significant difference

abstract kindle
#

How would I even start to learn it..

#

And are databases files that are just stored on my PC?

sage otter
#

Yes

#

They are on disk.

sage otter
sullen shoal
#

haha this guy still stuck mixing shit until its muffin

sage otter
#

???????

sullen shoal
#

told ya, just go with an actual database

#

nvm

abstract kindle
#

Okay, so how would I get started with a database?

quick gust
#

just me or discord doesn't show when Myxi is typing

abstract kindle
#

Might as well say fuck it and rewrite everything I've started xD

sage otter
#

You know SQL?

abstract kindle
#

Nope

sage otter
#

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.

quick gust
#

SQL shouldn't be hard, it's basic English to an extent

sage otter
#

you know a programming language that’s basically English. Cobol

sullen shoal
#

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

unkempt canyonBOT
#

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.

quick gust
sage otter
#

Types everything in a notepad and copy and paste

#

Just kidding. Idk.

quick gust
#

lmao

sullen shoal
#

maybe this

abstract kindle
#

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?

sullen shoal
#

first you gotta learn

#

the syntax

abstract kindle
#

Just write sample code and test it in offline?

sullen shoal
#

yes use the built-in one for now

#

offline basic project

novel bolt
#

is there a way to get current position of a song in ffmpeg?

sullen shoal
#

!ytdl

unkempt canyonBOT
#

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)
novel bolt
#

😥

dapper citrus
#

pwp

#

owo

novel bolt
#

hmm

sullen shoal
#

ur gonna get warned for that soon

#

read the rule carefully, it is still a help

heavy folio
#
        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

sullen shoal
#

check the url if its really of that size or not

heavy folio
sullen shoal
#

discord.Guild.banner returns discord.Asset

#

which has a method with_size

#

!d discord.Asset.with_size

unkempt canyonBOT
sullen shoal
#

it will return a new object and then you may get the url by discord.Asset.url

opaque sun
#

How do I import discord in python

#
import discord
#

That doesn't work

quick gust
#

have you installed discord?

slate swan
#

In the cmd prompt

#

pip install discord

#

@opaque sun

opaque sun
#

Yes

#

I did that

#

Still doesn't work

jade tartan
#

How to fix?

slate swan
#

typehint emoji in the func to discord.Emoji

#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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.
slate swan
#

hm

slate swan
#

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

quick gust
#

@slate swan

slate swan
manic wing
#

they purposely leave it ambiguous

slate swan
#

what does that mean?

manic wing
#

so everyone doesn’t go and push the limits to their max

manic wing
manic wing
slate swan
#

oh ok

manic wing
#

fetch_channel hits the api

slate swan
#

does get_channel freeze async because its not async function?

manic wing
#

because its searching cache

#

its not hitting an asynchronous api

slate swan
#

ok

#

what is the rate limit on fetch_channel?

#

well

#

time to see what the rate limit is myself snoopy

manic wing
quick gust
#

he literally told you, they dont tell you the ratelimits so people don't abuse the api

slate swan
#

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?

manic wing
manic wing
slate swan
#

oh ok

#

However, request response headers do contain data about ratelimits

slate swan
#

If they didnt there would be no way to properly handle them

manic wing
wheat heart
#

please help

slate swan
#

how can i from discord.app import Option

cobalt jacinth
#

what is discord bot whitelabel ?

slate swan
hybrid ruin
#

I need help

slate swan
hybrid ruin
cobalt jacinth
hybrid ruin
#

But it’s damn hard

cobalt jacinth
#

like customize it, change name , logo

hybrid ruin
cobalt jacinth
#

i am clueless

slate swan
slate swan
sullen shoal
quick gust
sullen shoal
#

yes

quick gust
#

second, its so easy wdym.....

sullen shoal
#

dont dm me

cobalt jacinth
#

is it possible to change name n logo of the bot in a particular server ?

sullen shoal
#

@hybrid ruin this is your exam not mine, you gotta do it yourself

slate swan
#

you can change nickname , but not usernames and logo for now

sullen shoal
#

then homework*

hybrid ruin
#

Practice but I don’t understand anything

slate swan
#

scaterx, what part of the problem do you not understand?

sullen shoal
slate swan
#

also , this channel is not related to that stuff

sullen shoal
#

will take around 5 hours

#

thats it

hybrid ruin
slate swan
#

just occupy any of them

#

How to run the code on behalf of the user?

hazy agate
#

oh

#

a

primal scarab
#

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 ?

tiny ibex
tiny ibex
primal scarab
#

Oh ok

tiny ibex
primal scarab
#

Like?

cobalt jacinth
tiny ibex
#

And send tweets like that yk

primal scarab
#

Oh yea ya I understand

#

Ok tnx

tiny ibex
silk drift
#

anyone wanna make an anti nuke

primal scarab
#

😃

wheat heart
#

pps help

#

pls

silk drift
#

with?

wheat heart
tiny ibex
wheat heart
#

pip install discord

#

not work

#

on android

silk drift
#

i cant see

silk drift
#

anything.

wheat heart
#

no

silk drift
#

that maybe why

wheat heart
#

i tried installing

slate swan
#

how do i make a slash command in a cog?

wheat heart
#

but error

silk drift
#

because the code needs to install the packages when you run the script

#

like .json

#

wdym error

#

what does it say

tiny ibex
#

You can't have slash commands in dpy

wheat heart
#

why

tiny ibex
#

Until you are using any 3rd party lib

wheat heart
#

how use him

tiny ibex
wheat heart
#

what

silk drift
#

just get a plugin

wheat heart
#

which?

silk drift
#

make a lib folder

tiny ibex
wheat heart
#

idkkk

silk drift
#

.

wheat heart
#

i watched videos

#

how to create py bot

velvet tinsel
#

Good morning

silk drift
velvet tinsel
#

Discord bot obviously

slate swan
silk drift
tiny ibex
velvet tinsel
#

Yes

slate swan
#

mk

velvet tinsel
silk drift
#

wdym

velvet tinsel
#

Tell him exactly how to code

silk drift
#

he knows how to code

velvet tinsel
#

Ok

#

Just give him a tutorial

silk drift
#

thats not what he needs help with

velvet tinsel
#

Or recommend something

#

He needs help with slash commands?

silk drift
#

u cant use slash commands in dpy

velvet tinsel
#

You can with an extension

wheat heart
velvet tinsel
silk drift
#

yea but he doesnt have a lib

velvet tinsel
#

Then install it

silk drift
#

yes

urban shell
#

hey guys, is there a way to get the id of the person you're replying to

velvet tinsel
#

What IDE is he using?

silk drift
#

told him that

velvet tinsel
#

Wdym

silk drift
tiny ibex
wheat heart
velvet tinsel
urban shell
slate swan
#

well yeah?

urban shell
#

I want the id of the person whose message I'm replying to

silk drift
#

does anyone want to make a anti nuke bot