#discord-bots

1 messages ยท Page 752 of 1

cloud dawn
#

You should use a for loop anyways this is very messy.

potent spear
#

agreed

cloud dawn
#

Or better syntax add some new lines, shorter lines

#

We don't do that here.

boreal osprey
#

also uh, my intellisense on vs code is not working, is there a fix for that

potent spear
#

for example

if member == None:
   member = ctx.author```
is basically
`member = member or ctx.author`
final iron
#

Send your code and question here

potent spear
boreal osprey
potent spear
#

maybe small bits, not all

boreal osprey
#

it had for it, but it doesn't work for me

maiden fable
#

Actually u counted them correct

#

What if the member has only one role? Then the roles variable will be an empty list

potent spear
boreal osprey
maiden fable
maiden fable
boreal osprey
#

then it shows that role

#

but if it has no role then it's a empty list

#

and it doesn't work

maiden fable
#

And that's when the value is nothing

#

U should instead do value=[<your list comprehension>] or "No Roles"]

boreal osprey
#

im no professional at coding :((

#

but the role i can do

#

welp

maiden fable
#
    emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]) or "No Roles", inline = False)
pliant gulch
#
    if member == None:
        member = ctx.author

    roles = [role for role in member.roles][1:]
``` these two lines can be done better
#

member = member or ctx.author like Sniper already mentioned

#

and just do members.roles[1:]

#

No need to rebuild the entire list

maiden fable
#

Yea that too

pliant gulch
#

Hunter I added something cool to my rewrite wrapper!

maiden fable
#

O, what's that?

pliant gulch
slate swan
#

collectors?

pliant gulch
#

Imagine using collectors with anti-raid stuff, like if a large amount of members join

#

that's gonna be amazing

maiden fable
#

So, in built anti raid system support?

pliant gulch
#

no

#

It's just a regular listener that waits for the event to be dispatched X amount of times

#

then it dispatches to the collector with all the data from each event

#

A collector

maiden fable
#

Ah

#

that's some advanced stuff, but good going!

pliant gulch
#

It was just a simple asyncio.Queue

#

๐Ÿ˜”

maiden fable
#

Well I never used asyncio as much

pliant gulch
#

!d discord.Member.move_to

unkempt canyonBOT
#

await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Moves a member to a new voice channel (they must be connected first).

You must have the [`move_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
maiden fable
#

Also since am kinda learning JS (svelte) nowadays, sooo

mossy warren
#

do you use pyautogui to make discord bots?

maiden fable
#

Btw @pliant gulch take a look at this, was posted in disnake server

pliant gulch
#

He also said something about pycord which made them really made lmao

#

I don't see how you can say "in the long run we wont be "just a fork" when your project is quite literally a fork

#

I'd take it seriously if they rewrite the entire code base

maiden fable
pliant gulch
maiden fable
#

๐Ÿ˜‚my man drank too much, being happy to get to maintain a proper wrapper lib

pliant gulch
#

Most of the pycord commits just contain like 5 or less lines of additions of deletions ๐Ÿ˜”

#

At least from the random recent commits lmao

#

Why do this by yourself

#

discord already moves people to AFK channels if they go AFK in the guild past the set time

#

into a set AFK channel you set in settings

#

Oh I see

#

But then users would just circumvent this by leaving themselves unmuted

maiden fable
#

Wait I have something for u

#

Uhhh nvm, it's not there for members

#

But that's only for the bot

#

What timer?

#

Lemme see...

#

!d discord.Member.voice

unkempt canyonBOT
#

property voice: Optional[discord.member.VoiceState]```
Returns the memberโ€™s current voice state.
maiden fable
#

Wait @hidden hazel

#

I am finding that thing

#

I think u can check if a member is talking

spring flax
#

For a ModMail bot, that works on when a user reactions it creates a channel with him and staff and the messages get sent between each the created channel and modmail channel, how exactly should one send the embeds between each channel?

maiden fable
#

!d discord.VoiceState.self_mute is the max I can find ngl

unkempt canyonBOT
maiden fable
#

Ah cool

#

Discord does that automatically

#

!d discord.VoiceState.afk

unkempt canyonBOT
patent lark
maiden fable
#

Yea that's what we are looking for @patent lark

patent lark
#

you can do this with other libraries, but discord.py doesnt have that feature as far as im aware.

#

negative.

maiden fable
#

Wait how with disnake?

pliant gulch
#

hmmm

maiden fable
#

"Do this with other libs"

pliant gulch
#

You might be able to actually lol

patent lark
pliant gulch
#

My wrapper can detect people speaking based on websocket messages

#

Since voice connection requires a websocket connection

maiden fable
#

Damn

#

That's gonna be a useful feature ngl

patent lark
#

i'd assume you could, as i dont find it impossible, but i dont think discord.py actually handles it for you.

pliant gulch
#

So you'd need to do stuff with the internal websocket client of the bot

maiden fable
#

Wait @hidden hazel

#

A lib which has voice receive might be able to help u

pliant gulch
#

give me a sec I can prob figure it out

maiden fable
#

Ah cool

pliant gulch
#

cause my wrapper was implementing voice receive but we only got the packets, haven't decoded them

#

๐Ÿ˜”

maiden fable
#

No ๐Ÿ˜‚

patent lark
#

what are you going to do when a user leaves themselves unmuted for points?

maiden fable
#

No

patent lark
#

credit them because you were too lazy to fix a bug within your system?

maiden fable
#

Give them a role Extra Intelligent Nerd

#

Or #Failure

#

๐Ÿคฃ

patent lark
#

or you could prevent it all by detecting when they speak?

#

well there are probably multiple solutions

#

that being one.

final iron
patent lark
final iron
#

Or am I misunderstanding

glad thicket
#

Hey how do you send a message when the TimeOutError occurs

final iron
glad thicket
#

Hey how do you send a message when the TimeOutError occurs

final iron
#

I actually really don't like that

patent lark
final iron
#

There has to be a lib in some language which has it implemented

patent lark
#

its not a feature that allows you to detect that. we are talking about, changing internals to receive this, or use another lib which may allow it.

#

there is.

pliant gulch
#

Ah yep found it

glad thicket
pliant gulch
#

The gateway sends the voice websocket an Operation code of 5

#

This is basically dispatched when a User is in a "speaking" state

#

You'd probably don't want to modify the websocket and listen for the OPCode

#

I was just curious

pliant gulch
#

I guess this is sort of a grey area

slate swan
#

i have a ticket system and whats supposed to happen is i type *createticket <#channel> <message> and that would create an embed with a ticket reaction so people could react to it and talk to staff in the private channel that gets made and whenever i press on the reaction, it makes a new role but it doesnt make a new channel https://mystb.in/RulingMedicaidAccessible.python

maiden fable
pliant gulch
#

potentially breaking everything. Overall undefined behaviour

slate swan
#

is there a discordrb discord?

pliant gulch
slate swan
#

what can i do with rb then๐Ÿ˜”

pliant gulch
#

Oh nevermind I was looking at the old repo

#

Looks like they moved the repo

#

oh... its a bit better, but hasn't had a commit since 4 months ago

slate swan
#

this one right

#

wait

#

theres a channel for it in the discord api server

slate swan
#

discordrb looks so clean and simple ngl

spring flax
#

For a ModMail bot, that works on when a user reactions it creates a channel with him and staff and the messages get sent between each the created channel and modmail channel, how exactly should one send the embeds between each channel?

storm junco
#

Hi together!
I am currently splitting my cogs because it starts to get messy. What is the best way to have variables shared within all files?
In the all-in-one cog I just loaded my settings from file into a global variable and wrote it back on changes. Now I can't do that because the settings inside different cogs would drift apart if they all change settings. But I don't really want to load the settings from file every time I need them.

spring flax
potent spear
spring flax
potent spear
#

the size doesn't matter

spring flax
#

though, how do I send messages between the DM channel and created staff channel, is what I'm confused about

potent spear
#

it's not because it's small, that you can use a txt or whatever

green dust
#

Is it possible to make a bot to send message to a channel on terminate

potent spear
potent spear
spring flax
potent spear
spring flax
green dust
potent spear
potent spear
spring flax
#

do you know chambur's modmail?

potent spear
# green dust OK cool. Tq

I'll save you some time
Overwrite Bot.close with what you would like to happen as the bot shuts down to implement "on_close" functionality.
Note: if you are not sub-classing it is recommended that you do so as to avoid over-complications.

class CustomBot(discord.Client):  # or inherit commands.Bot
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        ...

    async def close(self):
        # do stuff
        await super().close()```
potent spear
potent spear
#

else print the error
also, ctx comes first, then error

#

make sure you have the event decorator on top

vale wing
#

How is it decorated (and why not use elif)

#

The what

oblique cobalt
#

he meant elif in if..elif..else

#

LMAO

#

@instance.event

vale wing
#

@bot.listen('on_command_error') recommended

oblique cobalt
#

^

oblique cobalt
potent spear
#

why listen? so you can have multiple listeners for the same event?

vale wing
#

Why event?

oblique cobalt
potent spear
#

since you only need one...

oblique cobalt
#

on_command_error by default prints traceback

vale wing
#

I have listeners in all of my bots it doesn't raise errors

oblique cobalt
#

im saying print not raise

vale wing
#

It doesn't print anything

#

You can check by yourself

oblique cobalt
#

ill check when i get on PC

vale wing
#

@oblique cobalt I checked it for you (as you can see the console is empty even tho there are no events but only listeners)

sonic gale
#
async def on_member_join(member):
    embed = discord.Embed(description = f"\n\n[#915283231899795526](/guild/267624335836053506/channel/915283231899795526/)\n\n[#917113108420513842](/guild/267624335836053506/channel/917113108420513842/)\n\n[#912080645608587325](/guild/267624335836053506/channel/912080645608587325/)", color=0x36393E)
    embed.set_thumbnail(url = member.avatar_url)
    await ctx.send(f"welcome {member.mention}")
    await client.get_channel(912102049364209684).send(embed=embed)``` help with await ctx.send(f"welcome {member.mention}")
#

where would i put it

#

so send a message outside the embed

potent spear
#

this is the incorrect listener in a Cog / class

#

the docs will tell you what is

#

just look up Cogs and it'll be right ahead

waxen granite
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

waxen granite
#

somene pls take a look at this

potent spear
#

done

waxen granite
#

surgeryend = datetime.datetime(2022, 1, 13, tzinfo=ist)

#
            elif localdate > obgend:
                def surgery(localdate, surgeryend):
                    return (localdate - surgeryend)
                days = f"{surgery(surgeryend, localdate)}"
                medicinestart = surgeryend - localdate
                if medicinestart.days <= 1:
                    await message.reply("Your Next posting `Medicine`, starts tomorrow.")
                else:
                    await message.reply(f"Current Posting: `Surgery`, {':'.join(days.split(':')[0:-1])} hrs to go.")
            elif localdate > surgeryend:
                def medicine(localdate, medicineend):
                    return (localdate - medicineend)
                days = f"{medicine(medicineend, localdate)}"
                cmstart = medicineend - localdate
                if cmstart.days <= 1:
                    await message.reply("Your Next posting `Community Medicine`, starts tomorrow.")
                else:
                    await message.reply(f"Current Posting: `Medicine`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
potent spear
#

you don't have to put anything between the (), you can just it like an event, not a listen

waxen granite
#

in the 1st 1lif

#

elif*

#

it worked correctly

#

now that the date is more than 13/01/2022

#

it should triger the elif localdate > surgeryend:

#

but

potent spear
#

just print the statement itself, and you'll see if the outcome is as expected

#

print(localdate > surgeryend)

waxen granite
#

when i am sending the msg posting it says await message.reply("Your Next posting Medicine, starts tomorrow.")
when it should send await message.reply(f"Current Posting: Medicine, {':'.join(days.split(':')[0:-1])} hrs to go.")

potent spear
#

@bot.event outside of a class
is equal to
@commands.Cog.listener()
inside of a Cog

#

you have to add self as an argument in that method, you're in a class

#

if that error didn't pop up, you have some messed errorhandlers somewhere

waxen granite
potent spear
#

you can just print every variable and check if it's what you want it to be
that way, you know what's wrong

waxen granite
#

jsut a sec i messed up while printing xd

#

print (localdate > surgeryend) is True

#

since its true it shpuld trigger the

            elif localdate > surgeryend:
                def medicine(localdate, medicineend):
                    return (localdate - medicineend)
                days = f"{medicine(medicineend, localdate)}"
                cmstart = medicineend - localdate
                if cmstart.days <= 1:
                    await message.reply("Your Next posting `Community Medicine`, starts tomorrow.")
                else:
                    await message.reply(f"Current Posting: `Medicine`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
#

but

copper yarrow
#

How can I make a marry command and it will show whom you married when you type !marrage

waxen granite
#

its still triggering this only

elif localdate > obgend:
                def surgery(localdate, surgeryend):
                    return (localdate - surgeryend)
                days = f"{surgery(surgeryend, localdate)}"
                medicinestart = surgeryend - localdate
                if medicinestart.days <= 1:
                    await message.reply("Your Next posting `Medicine`, starts tomorrow.")
                else:
                    await message.reply(f"Current Posting: `Surgery`, {':'.join(days.split(':')[0:-1])} hrs to go.")```
#

@potent spear

waxen granite
potent spear
waxen granite
#

the value is okay

potent spear
potent spear
waxen granite
#

well yes but

#

the point is

#

it shoul consider the elif localdate > surgeryend: first

copper yarrow
potent spear
waxen granite
#

if localdate <= obgend:
elif localdate > obgend:
elif localdate > surgeryend:

#

i have these 3 statements

potent spear
waxen granite
potent spear
copper yarrow
#

!snipe

#

Snipe pls

potent spear
copper yarrow
#

Anyone

copper yarrow
copper yarrow
#

I need a database for marriage command?

waxen granite
#

how can i solve this :3

potent spear
potent spear
#

if you do, you'll just have to store in a db when you get married and via the "marriage" it'll check who you married to in the db or whatever you like

shadow wraith
#

wait how do i make the bot send a message with all the items in a list without it sending an item each message, like i want all the items to be in 1 message

potent spear
#

google python str.join

shadow wraith
#

i kinda didn't code in python for a while

shadow wraith
slate swan
#

!join

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
potent spear
#

or that^^
who needs google?

shadow wraith
slate swan
#

I'm sure 40% of discord.py code on stackoverflow is bad

shadow wraith
#

but i use disnake tho

honest shoal
#

stackdidnotflow

shadow wraith
slate swan
#

doesn't matter , Disnake is derived from discord

#

Guys can someone help me?

#

Sure

#

its about this

#

I want to duplicate these to my code

    if any(word in message.content for word in["Ghoul", "Town"]):
        await message.delete()
        sent_message = await message.channel.send('<@&926037413669769228> There is a raid in Ghoul Town starting within 15 minutes.')
        hist[message.author.id] = sent_message
      


    if "MASSIVE" in message.content:
        if message.author.id in hist:
            await message.delete()
            await hist[message.author.id].edit(content="**MASSIVE** - <@&926037413669769228> There is a **MASSIVE** raid in Ghoul Town starting within 15 minutes.")  ```
#

but this lines will be changed:
if any(word in message.content for word in["Ghoul", "Town"]):

#

sent_message = await message.channel.send('<@&926037413669769228> There is a raid in Ghoul Town starting within 15 minutes.')

#

await hist[message.author.id].edit(content="**MASSIVE** - <@&926037413669769228> There is a **MASSIVE** raid in Ghoul Town starting within 15 minutes.")

vale wing
#

Why is it like

in[...]```
There should be a space
slate swan
#

space on what?

vale wing
#

In this case it will work anyway but it is not following code style conventions I am pretty sure

#
in [...]```
slate swan
#

oh

#

this one?
in["Ghoul", "Town"]):

vale wing
vale wing
slate swan
#

i want it to detect another specific words instead of
["Ghoul", "Town"])

slate swan
vale wing
#

Create a list of those words and store it somewhere if you would like to

slate swan
#

how can i create a list?

vale wing
#

Do you know python well?

slate swan
#

nope

#

๐Ÿ˜… .

vale wing
#

Then I don't recommend to start learning it from a discord bot, start with smaller projects

#

It requires intermediate python knowledge because it is an advanced asynchronous application and just copying code from everywhere won't give you much knowledge

slate swan
#

okay

shadow wraith
#

i am

#

bored

slate swan
spring flax
#

without using a database, how would be the best way to have a list of ID's and check/add to that list. Would a json file be okay for this?

shadow wraith
#

isn't json kinda a db?

karmic lintel
#

hmm you can say but not for big projects

quick gust
#

share code when

slate swan
#

dm

quick gust
#

no dm

#

send it here

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

quick gust
#

@slate swan I won't be helping u in DMs

slate swan
#

hwy

#

ok

#
async def update_data (users, user):
   if not f'{user.id}' in users:
    users[f'{user.id)'] = {}
    users[f'{user. id}']['experience'] = 0
    users[f'{user. id}']['level'] = 1

async def add_experience(users, user, exp):
    users[f'{user. id}', ['experience'] +- exp

async def level_up(user, users, message):
    with open('levels.json', 'r') as g:
        levels = json.load(g)
experience = users[f'{user. id}']['experience']
lvl_start = users[f'{user. id}']['level']
lvlend = int(experience ** (1/4))
if lvl start < lvl_end:
    await message.channel.send(f'{user.mention} has leveled up! **TO LEVEL - {lvl_end}')
    users [f'{user.1d}']['level'] = lvl_end```
quick gust
#
  1. why is there an event decorator
  2. the indentation seems inside the level_up func
spring flax
#
  1. a database is better than a json for a levelling system
shadow wraith
#

i dont think there is spacing betwee nthe parenthesis and the name

slate swan
#

ive fixed that i think but i got a new error and i cant fix it ig

maiden fable
#

What's the error?

#

id*

#

Not 1d

slate swan
#

.

maiden fable
#

Lol

#

Oh

slate swan
#

ik

maiden fable
#

U can't find the file?

slate swan
#

ye

maiden fable
#

Weird... what's <fstring>

dire folio
#

Sounds like replit is doing good

maiden fable
#

Facts

slate swan
dire folio
#

My best guess is that it's gonna be in the users.json file

slate swan
dire folio
#

I have not the slightest clue how to help sorry

slate swan
#

same

visual island
#

@slate swan look at line 104

#

you wrote 1d

slate swan
#

i saw it

prime inlet
#

what do you recommend I start with when coding a disocrd bot, bcos I wanna make just a simple one for a server for friends

humble granite
#

Hi! I get a bearer (or smth like that) from a function.
Looks like this: b'["hello","welcome"]'
How can i count how much words (strings) are in there?

slate swan
#

a new error ๐Ÿ˜

vale wing
#

It's speaking for itself

slate swan
vale wing
#

!indents

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

quick gust
#

what did I say? your indents are wrong in the level_up func

slate swan
#

?

quick gust
#

what part of that sentence do you not understand

icy mango
#

hi

#

there was a bot called r.danny right?

humble granite
#

Hi! I get a bearer (or smth like that) from a function.
Looks like this: b'["hello","welcome"]'
How can i count how much words (strings) are in there?

slate swan
#

can someone help me with this?

        await message.delete()
        sent_message = await message.channel.send('test')
        hist[message.author.id] = sent_message

    if "star" in message.content:
        if message.author.id in hist:
            await message.delete()
            await hist[message.author.id].edit(content = "testing")```
if i type "hope", the message gets deleted and the bot sends a message "test". and if i type "star", the message gets deleted and the bot edits the message "test" into "testing".
#

i have a problem, if i duplicate that code

humble granite
#

you are closing the task

#
if any(word in message.content for word in "hope"):
        await message.delete()
        sent_message = await message.channel.send('test')
        hist[message.author.id] = sent_message

        if "star" in message.content and message.author.id in hist:
            await message.delete()
            await sent_message.edit("testing")

should work with that

slate swan
#

no wait, thats not my problem

#

and change something into this,

        await message.delete()
        sent_message = await message.channel.send('test')
        hist[message.author.id] = sent_message

    if "star" in message.content:
        if message.author.id in hist:
            await message.delete()
            await hist[message.author.id].edit(content = "pound")```
humble granite
#

@slate swan
this should work

hist = {}

if any(word in message.content.lower() for word in "hope"):
        await message.delete()
        sent_message = await message.channel.send('test')
        hist.append(messager.author.id)

        if "star" in message.content and message.author.id in hist:
            await message.delete()
            await sent_message.edit("testing")
slate swan
#

i'll try it

humble granite
#

put the hist = {} outside the on_message event

slate swan
#

my problem is that when i duplicte that code into my script and change the words inside the "-". it contradicts each other

humble granite
#

you don't have to duplicate the code

#

and you are making a for for one string

#

should look like this if "hope" in message.content

twin moon
#

Button links in nextcord

maiden fable
unkempt canyonBOT
#

nextcord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`nextcord.ui.View`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.View "nextcord.ui.View"), the [`nextcord.ui.Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") being pressed and the [`nextcord.Interaction`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction "nextcord.Interaction") you receive.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.Button "nextcord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
twin moon
maiden fable
#

It's easy

heavy radish
#

Anyone have any sample coding of reading embed? Any code. Just trying to learn how to. DM me please.

vast spruce
#

Guys I need help, I would appreciate everyone who could help me.

I got reported on my main for being underage. I appealed it, and it was been a day now. I heard many people never got their accounts back.

So, in case my account gets deleted in 14 days (since I heard when it gets disabled it gets deleted in 14 days) only thing I can do is transfer ownership to other account but it MUST have Moderator/Admin perms.

Well this is a problem, nobody on the Server including bots have those perms (they have mod ones).

Only one that has Admin perms is bot I made, and I have my token. So is there a way I can code a bot to make a role with admin perms and give me it? Thank you.

boreal ravine
unkempt canyonBOT
boreal ravine
#

also if your bot has admin, why cant it just unban you from the guild pithink

vast spruce
vast spruce
vast spruce
#

I sent them proof of me kot being underage.

boreal ravine
# vast spruce Yes I am.

your bot needs to make a role with admin permissions and then you'd need to give it to yourself

maiden fable
vast spruce
#

Last one is problem for me.

#

So that's the idea I got

boreal ravine
boreal ravine
#

only the owner of the server can transfer owner

vast spruce
#

It owners account gets deleted

twin moon
boreal ravine
#

oh

heavy radish
vast spruce
#

You can request from discord to transfer

#

But new accs needs admin perms

#

So can I make bot to make a role with admin perms and give me that role on alt?

twin moon
vast spruce
#

That's my question

boreal ravine
heavy radish
#

Brb

vast spruce
twin moon
#

anyone know asyncpraw

boreal ravine
manic wing
slate swan
#

guys can someone help me?

twin moon
maiden fable
slate swan
#

this is my code

        await message.delete()
        sent_message = await message.channel.send('Ghoultest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
    if any(word in message.content for word in ["Slayer", "Army"]):
        await message.delete()
        sent_message = await message.channel.send('Slayertest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Slayertest")```
maiden fable
#

?

#

Ah the any() is wrong

#

any(word for word in message.content if word in [])

slate swan
#

oh

maiden fable
#

Ig that's the main issue rest idk

slate swan
#

thats not my issue

#

my problem is that

maiden fable
#

?

heavy radish
twin moon
slate swan
#

When i type Ghoul Town it executes the first if "MASSIVE" in message.content:. and when i type Slayer Army it executes the second if "MASSIVE" in message.content:. But the issue is, when i type Slayer Army again, it executes the first if "MASSIVE" in message.content: not the second if "MASSIVE" in message.content:.

heavy radish
maiden fable
maiden fable
#

Also u sure u r writing Slater Army and not Slayer army?

tacit token
#

Hello! Anyone who knows how to use buttons, can I talk to them privately?

maiden fable
#

Sure, ig

twin moon
opaque minnow
#

Hey guys, I'm trying to work with the discord.py API and learn some fun ways to use it, I'm currently trying to grab all servers and all channels within those servers and write them to folders and files.

I've came across 2 issues, the first is that it seems to be attempting to write all channels for all servers into every server folder (instead of their own independent folders). The second is that the txt files seem to error once they encounter an emoji.

Error:

[ERROR]: Command raised an exception: OSError: [Errno 22] Invalid argument: 'C:\\Users\\me\\Desktop\\main2/logs/HackerOne/๐Ÿ‘ธGirls-Only ๐Ÿšซ๐Ÿ† <โ€” Stinky.txt'

Code:

    await ctx.message.delete()
    async for guild in client.fetch_guilds():
        os.mkdir(f'logs')
        os.mkdir(f'{pathlib.Path(__file__).parent.resolve()}/logs/{guild}')
        for channels in client.get_all_channels():
            ff = open(f'{pathlib.Path(__file__).parent.resolve()}/logs/{guild}/{channels}.txt', 'w', encoding='utf-8')
            ff.write(f'test')
    await asyncio.sleep(25)  
    print(f'{Fore.GREEN}Success!')

(yes I know this is awful but I'll clean it up with error handling when it's behaving as it should)
I should add that without writing the text files, this will create a folder for every server. It's just struggling to handle emojis it seems and adding all servers channels into each folder

maiden fable
#

Why fetch_guilds?

#

!d discord.Client.guilds exist

unkempt canyonBOT
#

property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
opaque minnow
tacit token
#

Hello! Can I talk to someone who used discord components?

opaque minnow
#

I've tried literally everything I can think of by this point and now I'm just stuck

#

Ran out of ideas

slate swan
twin moon
slate swan
twin moon
#

can I put a var in a decorator inside a class?

#
@nextcord.ui.Button(label="Reddit",style = nextcord.ButtonStyle.green,url = total_link) #total_link
async def memedata(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):```
slate swan
twin moon
slate swan
#

CODE:

        await message.delete()
        sent_message = await message.channel.send('Ghoultest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
    if any(word in message.content for word in ["Slayer", "Army"]):
        await message.delete()
        sent_message = await message.channel.send('Slayertest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Slayertest")

ISSUE:
When i type Ghoul Town it executes the first
if "MASSIVE" in message.content:
and when i type Slayer Army it executes the second
if "MASSIVE" in message.content:
. But the issue is, when i type Slayer Army again, it executes the first
if "MASSIVE" in message.content:
not the second
if "MASSIVE" in message.content:

My opinion
i think the bot doesnt recognize the 2nd
if "MASSIVE" in message.content:
and only executes the 1st
if "MASSIVE" in message.content:
since it's placed higher than the second one.

How can i fix it guys? thanks for helping!

copper yarrow
#

Bro how can I remove add to server feature from my bot

maiden fable
copper yarrow
maiden fable
maiden fable
slate swan
#

if any(word in message.content for word in ["Ghoul", "Town"]):
or
if "MASSIVE" in message.content:
?

maiden fable
#

No

#

if MASSIVE in message.content

copper yarrow
#

Hiw

slate swan
#

about that

copper yarrow
#

Help me

maiden fable
#

Only one of them will execute, the first one, since that's first in order

copper yarrow
#

Should I enable public bots in bots section

maiden fable
#

Yea

copper yarrow
#

Why?

maiden fable
#

U need to make it a public bot

copper yarrow
#

I don't want anyone to add it

maiden fable
#

Then forget about the Add to Server button

copper yarrow
copper yarrow
maiden fable
copper yarrow
#

How to remove

copper yarrow
maiden fable
#

No

slate swan
errant shuttle
#
# I imported the other modules
async def mute(self, ctx: commands.Context, member: Member, timer="15m", *, reason):
  long = humanfriendly.parse_timespan(timer)
  await member.edit(
  timeout=utils.utcnow() + datetime.timedelta(seconds=long)
)

I am getting this error (I never got it before)```
File "/home/runner/Efendo-Bot-Source-Code/modules/mod/cog.py", line 130, in mute
await member.edit(
TypeError: edit() got an unexpected keyword argument 'timeout'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/bot.py", line 995, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 895, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/nextcord/ext/commands/core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: edit() got an unexpected keyword argument 'timeout'```

This command used to work before but it dosn't work anymore.
Any idea what is wrong with it?

maiden fable
slate swan
maiden fable
errant shuttle
maiden fable
#

Wrong nextcord version

#

It's a common issue to have a version mismatch

errant shuttle
#

@maiden fable what is the correct nextcord version?

slate swan
# maiden fable Idk what u tryna do, sooo

so basically, if i type Slayer Army, it will execute the second
if "MASSIVE" in message.content:
since it's under the if-statement of
if any(word in message.content for word in ["Slayer", "Army"]):
and when i type Ghoul Town, it will execute the first
if "MASSIVE" in message.content:
since it's under the if-statement of
if any(word in message.content for word in ["Ghoul", "Town"]):

maiden fable
#

Ah the indentation sucks

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

maiden fable
#

The indentation is all messed up

#

This is how it's shown in my mobile

#

So format your code with codeblocks plz

slate swan
#

oh

upbeat otter
#

use three backticks

maiden fable
#

Yea

slate swan
#

i ask again lol

maiden fable
#
if any(word in message.content for word in ["Ghoul", "Town"]):
        await message.delete()
        sent_message = await message.channel.send('Ghoultest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Ghoultest")
#----------------------------------------------------------------------------
    if any(word in message.content for word in ["Slayer", "Army"]):
        await message.delete()
        sent_message = await message.channel.send('Slayertest')
        hist[message.author.id] = sent_message

    if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "Massive Slayertest")
#

Did it for u

#

See yr indent

heavy radish
#

Where is my intend wrong?

slate swan
#

is there anyway i can put this code

if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "**MASSIVE** - <@&926037277833048115> There is a **MASSIVE** raid in Slayer Army starting within 15 minutes.")

under this one?

if any(word in message.content for word in ["Slayer", "Army"]):
        await message.delete()
        sent_message = await message.channel.send('<@&926037277833048115> There is a raid in Slayer Army starting within 15 minutes.')
        hist[message.author.id] = sent_message

so when this

if any(word in message.content for word in ["Slayer", "Army"]):
        await message.delete()
        sent_message = await message.channel.send('<@&926037277833048115> There is a raid in Slayer Army starting within 15 minutes.')
        hist[message.author.id] = sent_message

is executed
this

if "MASSIVE" in message.content:
      await message.delete()
      if message.author.id in hist:
            await hist[message.author.id].edit(content = "**MASSIVE** - <@&926037277833048115> There is a **MASSIVE** raid in Slayer Army starting within 15 minutes.")

will also execute

maiden fable
upbeat otter
spring flax
#

Just to confirm, one can have two @bot.listen() functions in the same main file right? I seem to have forgotten

upbeat otter
heavy radish
upbeat otter
spring flax
upbeat otter
#

keep the events same

spring flax
#

what you can't do is use two on_message events for @bot.event then, correct?

spring flax
#

okay thanks

upbeat otter
# spring flax okay thanks
@bot.listen("on_message")
async def first_on_message: pass

@bot.listen("on_message")
async def second_on_message: pass

welcome

slate swan
#

guys help me๐Ÿ˜ญ

#

!ask

maiden fable
#

@slate swan his/her code and problem is above

slate swan
maiden fable
#

Uh

slate swan
#

word in message.content are the values it will return , which would be a bool

maiden fable
#

!e
if any(word in "slayer" for word in ["Slayer", "Army"]):
print(1)

#

It still works (:

unkempt canyonBOT
#

@maiden fable :warning: Your eval job has completed with return code 0.

[No output]
maiden fable
#

See

slate swan
#

so what problem happens with the 2nd statement>

flat solstice
#

So I have this command (going to be a task event which runs every 6 - 24 hours, eventually) which searches through a channels history to find msgs that have embeds which match a list of keywords. I

  1. want my bot to look through the fetched msgs chronologically (oldest to newest)
  2. then for every message in that list I want to check if the message ID is not in my list of checked messages
  3. then I want it to check if the author of the msg is the same as the provided ID
  4. then I want it to check if the message contains a embed (It should do every time but doing this to be on the safe side)
  5. then I want it to check if any of the words in my key_words list appear in the embeds title
  6. if the key_words do appear then I want it to construct a new embed from the field values of the original embed
  7. then I want it to add the ID of the message it just checked to my list of checked msgs so that it won't check it again in future
    I think I have all of that logic correct but does someone mind checking over my code to double check this for me?
    I also have some additional stages that I'm not too sure how to implement so some idea's on how I could do them would be appreciated.
  8. I would like to be able to know which of my key_words it triggers on so that I can add that to my new embed inside of the {action} variable
  9. I would like to write the datetime timestamp of the last checked message to my last_chacked variable so that it won't check msgs before that again (jut saving on having duplicate new embeds)
    Below is my code, thank for you reading```py
    @commands.command()
    @commands.has_permissions(administrator = True)
    async def moderation_logs(self, ctx):
    key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] # Add in Captilised versions of each word to account for the Dyno logs
    checked_logs = []
    case_count = 0
    last_checked = 0
    #dict = {}
    moderation = self.bot.get_channel(id = 885569667861717042)
    clifford_log = self.bot.get_channel(id = 500768218257031168)
with moderation.channel.typing():
    messages = await clifford_log.channel.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
    for message in messages[0:]: # Making bot search history chronologically
        if message.id not in checked_logs:
            if message.author.id == 776782769312628746:
                if len(message.embeds) > 0:
                    if key_words in message.embeds[0].title:
                        embed = discord.Embed(title = f"Case {case_count} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
                        embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
                        embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
                        embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
                        embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
                        if message.embeds[0].fields[3]:
                            embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
                        if message.embeds[0].fields[2]:
                            embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
                        checked_logs.append(message.id)
                        await moderation.send(embed = embed)```
slim whale
#

hi, i have a server with 1700 bans and i need help with an unban all command,

@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def unban(ctx):
    server=ctx.guild
    ban_list=await bot.get_bans(server)
    await ctx.send('Desbaneando a todos los miembros.')
    for member in ban_list:
      await bot.unban(server,member)```
#

The bot doesn't unban anyone

#

And it doesn't print any traceback

silver wolf
#

Itโ€™s guild.bans() not get_bans()

twin moon
#
class RedditLink(nextcord.ui.View):
    def __init__(self,link,permalink):
        self.reddit_link = link
        self.permalink = permalink
        self.total_link = self.link + self.permalink

    @nextcord.ui.Button(label="Reddit",style = nextcord.ButtonStyle.green,url = self.total_link)
    async def link(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
        pass```
 it doesent find self.total_link
slim whale
silver wolf
#

Just bans(). No parameters

slim whale
#

okay

silver wolf
#

Make sure the tutorial u looked at is up to date

slim whale
#

so the server=ctx.guild is innecesary?

silver wolf
#

Technically yes, but the way u have it is fine

slim whale
#

okay

#

thanks!

twin moon
silver wolf
#

Doesnโ€™t it have bot.guilds?

#

Which is a list

#

.bans() is for a single server

slim whale
#

await ctx.guild.unban(member) can i do it like this?

#

@bot.command(pass_context=True)
async def unban(ctx):
  if ctx.author.id == 626127081419571206 or 931999712012275732:
      ban_list=await bot.guild.bans()
      await ctx.send('Desbaneando a todos los miembros.')
      for member in ban_list:
      await ctx.guild.unban(member)
  else:
    await ctx.send('ยกNo tienes permisos para ejecutar ese comando!')```
#

it looks like this

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.")
silver wolf
vague grove
#

hey guys how can i make my slash commands say something to the user and only they can see it

vague grove
twin moon
vague grove
#

discord_slash

twin moon
#

use nextcord

#

or disnake

vague grove
#

oh

#

why not

twin moon
vague grove
#

lol

#

so you can hide messages with discordpy?

twin moon
vague grove
twin moon
#

instead of discord

#

nextcord

vague grove
#

will all my code break when i do upgrade

twin moon
#

discord.Embed -> nextcord.Embed

twin moon
vague grove
#

or just import nextcord as discord

twin moon
vague grove
#

so im guessing nextcord is better than disnake?

twin moon
#

I use nextcord

vague grove
#

alr ill peek around and make a decision

#

ty

flat solstice
#

So I have this command (going to be a task event which runs every 6 - 24 hours, eventually) which searches through a channels history to find msgs that have embeds which match a list of keywords. I

  1. want my bot to look through the fetched msgs chronologically (oldest to newest)
  2. then for every message in that list I want to check if the message ID is not in my list of checked messages
  3. then I want it to check if the author of the msg is the same as the provided ID
  4. then I want it to check if the message contains a embed (It should do every time but doing this to be on the safe side)
  5. then I want it to check if any of the words in my key_words list appear in the embeds title
  6. if the key_words do appear then I want it to construct a new embed from the field values of the original embed
  7. then I want it to add the ID of the message it just checked to my list of checked msgs so that it won't check it again in future
    I think I have all of that logic correct but does someone mind checking over my code to double check this for me?
    I also have some additional stages that I'm not too sure how to implement so some idea's on how I could do them would be appreciated.
  8. I would like to be able to know which of my key_words it triggers on so that I can add that to my new embed inside of the {action} variable
  9. I would like to write the datetime timestamp of the last checked message to my last_chacked variable so that it won't check msgs before that again (jut saving on having duplicate new embeds)
    Below is my code, thank for you reading```py
    @commands.command()
    @commands.has_permissions(administrator = True)
    async def moderation_logs(self, ctx):
    key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] # Add in Captilised versions of each word to account for the Dyno logs
    checked_logs = []
    case_count = 0
    last_checked = 0
    #dict = {}
    moderation = self.bot.get_channel(id = 885569667861717042)
    clifford_log = self.bot.get_channel(id = 500768218257031168)
with moderation.channel.typing():
    messages = await clifford_log.channel.history(oldest_first = True, limit = None, after = last_checked).flatten() # 10000
    for message in messages[0:]: # Making bot search history chronologically
        if message.id not in checked_logs:
            if message.author.id == 776782769312628746:
                if len(message.embeds) > 0:
                    if key_words in message.embeds[0].title:
                        embed = discord.Embed(title = f"Case {case_count} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp)
                        embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url)
                        embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url})
                        embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True)
                        embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True)
                        if message.embeds[0].fields[3]:
                            embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value)
                        if message.embeds[0].fields[2]:
                            embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value)
                        checked_logs.append(message.id)
                        await moderation.send(embed = embed)```
surreal sierra
#

if I have my code shared up in different files and one file is for all events. how do I load the events in the main file so it all works? do I have to use cogs, in that case how would it work? or is there an another way to do it?

misty vault
slim ibex
#

replace folder.folder with the path to the file

slim whale
#

still need help with the unban all command, i have this

@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  ban_list = ctx.guild.bans()
  await ctx.send('Desbaneando a todos los miembros.')
  for member in ban_list:
    await ctx.guild.unban(member)```
misty vault
#

it just says this

#

i copy and pasted from the pypi

slim ibex
surreal sierra
misty vault
slim whale
slim ibex
#

Do it on cmd @misty vault

slim ibex
misty vault
#

??

#

where

slim ibex
surreal sierra
vague grove
#

how long does discord take to pop up slash commands on all my servers

#

all servers the bots in

slim whale
vague grove
slim ibex
#

You have to specify guild ids in the decorator, for testing purposes. There is probably another way to do it if you want it in all guilds

vague grove
#

and once i update the slash commands, it also takes 1 hour?

misty vault
#

i dont think so

slim ibex
drifting arrow
#

@commands.has_any_role(*_CONFIG["bot_manager"])
How do I update that variable? I manage to update it using a command but it doesnt respond to the new role I assign. I am typing the role correctly.

slim whale
#

i will try and i tell u

slim ibex
#

There is probably an issue with the event loop

vague grove
#

with a list it just appends

slim whale
#

same thing @slim ibex

slim ibex
#

ye I didnโ€™t expect it to work right away

#

There is some issue with the actual code

slim whale
#

with the bot code? or just the cmd code

slim ibex
#

lemme see

#

the command

slim whale
#
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  ban_list = await ctx.guild.bans()
  await ctx.send('Desbaneando a todos los miembros.')
  for member in ban_list:
    await ctx.guild.unban(member)```
slim ibex
#

I would probably pass in member as a nob-keyword arg and make sure to use the member name and discriminator because that is how you will unban the user

misty vault
slim whale
#
@bot.command()
async def test(ctx):
  await ctx.send('adsa')```this doesnt work XD
slim ibex
#

oh well then itโ€™s an issue with the bot itself

#

are you in cogs?

misty vault
#

where is cmd

slim ibex
#

Command prompt

slim whale
slim ibex
#

YeahX then itโ€™s an issue with the bot itself

#

maybe token or something idk

slim whale
#

no bc the logs work

slim ibex
#

Ye I was gonna get to that

misty vault
slim ibex
#

Windows+R and type CMD

slim whale
#

so how can i make it return the list of members

slim ibex
#

You donโ€™t want a list of members if you only want to unban one at a time

#

Thatโ€™s why I said you have to access the ban list like you already are and use the member name and discriminator

slim whale
misty vault
#

it says pip is not recognized as a intern or extern command

slim ibex
#

@misty vault you prolly donโ€™t have python installed properly

misty vault
slim ibex
#

and you also will need member as a non keyword arg in the function parameter

slim whale
#
for member in ban_list:
    member= f"{member.name}#{member.discriminator}"
    await ctx.guild.unban(member)``` like this?
slim ibex
#

Or just some sort of arg

#

I mean you COULD do it that way

#

Itโ€™s just you need the member argument if you want to specify the user to unban while typing the command

#

I believe so

slim whale
#
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  ban_list = await ctx.guild.bans()
  await ctx.send('Desbaneando a todos los miembros.')
  for member in ban_list:
    member= f"{member.name}#{member.discriminator}"
    await ctx.guild.unban(member)```so this should work?
#

i will host it in another bot bc it dont works and idk why (i did something wrong with the logs)

slim ibex
#

Do you know what an argument/parameter is?

#

You could try it and see if it works

copper zodiac
#

this is giving me a KeyError for 'formats'? how do i go about fixing that?

slim whale
#

async def a(ctx,a:str=None)

#

but i only want to unban everyone

slim ibex
#

OH

slim whale
# slim ibex OH

can i invite u to replit and u help me? bc i thing its cause of the logs

#

and i dont know why

slim ibex
#

First you want to reference the server, and next reference the ban list for said server

#

then you want to loop over every member in the ban list and unban them

drifting arrow
#

Is there any way for me to auto-reload a cog without needing to run a command?

slim ibex
#

ye prettt much

slim whale
#

ban_list = await server.guild.bans() ?

slim ibex
#

no

slim whale
#

how it would be?

slim ibex
#

use get_bans(server)

#

donโ€™t forgot the bot.

#

hmm

slim whale
#

bot.get_bans(server)

slim ibex
#

see if it works

#

After that loop over every member on ban list

#

And unban them

tacit token
#

anybody?

slim whale
#
@bot.command()
@commands.has_permissions(administrator=True)
async def unban(ctx):
  server=ctx.guild
  ban_list = await bot.get_bans(server)
  await ctx.send('Desbaneando a todos los miembros.')
  for member in ban_list:
    member= f"{member.name}#{member.discriminator}"
    await ctx.guild.unban(member)```
#

it doesn't

drifting arrow
slim whale
#

@slim ibex can i invite u to the replt?

slim ibex
#

not home Iโ€™m on my phone rn

slim whale
#

oh

#

like the @bot.command doesnt work bc of the logs

slim ibex
#

remove the member variable

#

where do you declare the bot variable

slim whale
#

bot = commands.Bot(command_prefix=".", intents=intents, owner_id=725708506556268605,help_command=None)

tacit token
slim ibex
#

did you import intents

#

and if you want all intents do, Intents.all()

slim whale
#

intents = discord.Intents.all()

#

yes but i think its for the message logs

tacit token
#

so nobody, noproblem

slim ibex
#

That wasnโ€™t needed

tacit token
#

where? 5014_MonkaBinoculars

#

a fact thus uses the interaction of the dadjoke so that it is not the same time

slim ibex
#

Which line raises the error

tacit token
#

None of them, they just run. However, when the fact is above the nanny, fact uses nannyjos, vice versa when it writes an error code under the button.

#

google translate

slim ibex
#

it has to do something with the instance (self)

tacit token
#

so i invite u maybe to 1 random test server and i show u

surreal sierra
#

Im trying to load my commands from a different file to the main file with classes. its not working, Im guessing I did something wrong but Im not sure what I did wrong. I got it like this


class vc_c(commands.Cog):

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    # Joins VC
    @commands.command()
    async def join(ctx):
        if ctx.author.voice is None:
            await ctx.send(f"Please, may {username} join a voice channel for me to direct to!")

        voice_channel = ctx.author.voice.channel
        if ctx.voice_commands is None:
            await voice_channel.connect()
        else:
            await ctx.voice_commands.move_to(voice_channel)

def setup(bot: commands.Bot):
    bot.add_cog(vc_c(bot))

Main file here (I didnt show the whole main file bcz its just so many imports and other shit):

bot.load_extension("vc_c")

print("Online")
bot.run('TOKEN')
slim ibex
tacit token
#

btw ty, i try remove from cogs and import for the main

surreal sierra
slim ibex
#

but are they in the same folder

#

or are the cogs in a deeper folder

surreal sierra
#

ah, yea all of them is in same folder

slim ibex
#

something like

#

oh ok

surreal sierra
#

here u see

slim ibex
#

I would make a cogs folder tbh

#

Because then you can use the os module to load them

surreal sierra
#

I mean it wouldnt make any different?

slim ibex
#

ehh just more organized

surreal sierra
#

oh okay

slim ibex
#

I guess thatโ€™s just me

#

but this is what I mean

#

for filename in os.listdir("./src/cogs"):
if filename.endswith(".py"):
self.load_extension(f"src.cogs.{filename[:-3]}")

surreal sierra
#

ah, okay. then I would have to create a new folder and have all the cogs there, I will try with that thanks

surreal sierra
humble granite
#

how do I get every string from this binary?
'b["hello","world"]'

copper zodiac
#

help plz^

final iron
#

!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)
copper zodiac
#

noted

misty vault
#
  File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 328, in <module>
    dll = DLL("SDL2", ["SDL2", "SDL2-2.0", "SDL2-2.0.0"], os.getenv("PYSDL2_DLL_PATH"))
  File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 200, in __init__
    raise RuntimeError("could not find any library for %s (%s)" %
RuntimeError: could not find any library for SDL2 (PYSDL2_DLL_PATH: unset)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\zined\Downloads\Pokemon - Blue Version (UE)[!]\Sblerboy-Open-Source-main\sblerboy.py", line 3, in <module>
    from pyboy import PyBoy
  File "pyboy\__init__.py", line 14, in init pyboy.__init__
  File "pyboy\pyboy.py", line 1, in init pyboy.pyboy
  File "pyboy\core\__init__.py", line 6, in init pyboy.core.__init__
  File "pyboy\core\mb.py", line 1, in init pyboy.core.mb
  File "pyboy\core\sound.py", line 13, in init pyboy.core.sound
  File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\__init__.py", line 3, in <module>
    from .dll import get_dll_file, _bind
  File "C:\Users\zined\AppData\Local\Programs\Python\Python310\lib\site-packages\sdl2\dll.py", line 330, in <module>
    raise ImportError(exc)
ImportError: could not find any library for SDL2 (PYSDL2_DLL_PATH: unset)```
#

its giving me 765763574256475756 errirs right as i thought it worked

final iron
slim ibex
#

^

misty vault
#

i am motterally coding a bot

#

litterally

final iron
final iron
#

Does your error have anything to do with any relevant discord bot development libraries?

tacit token
cold sonnet
#

I couldn't do it -> unsolvable

#

nah jk

#

I'm trash

keen talon
vague grove
#

is there a way so i dont have to specify each server id for the bots slash commands?

vague grove
#

discord

honest shoal
#

dpy doesn't have slash commands

vague grove
#

well discord_slash

opaque minnow
bleak sparrow
#
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='p!')


@client.event
async def on_ready():
    print("Bot is on")

client.run = ('TOKEN')
``` I got a new pc and i tried running a basic bot but all im getting is exit code 0 and im not sure why
opaque minnow
#

try

client.run('token', bot=False)
slate swan
#

How would I make it so that after I execute a command, the bot still answers me even though I don't have to do the command again?

Example:
Me: !start
Bot: How are you, p4nic?
Me: Fine/Bad
Bot: keep answering...

If I said "fine" it would do something. If I said "bad" it would do something else.

wicked atlas
wicked atlas
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
prime marten
#

anyone know how to make an shop/inventory system with sqlite3?

slate swan
#

ty

final iron
wicked atlas
#

hmmmmmmmm

opaque minnow
#

Not that I would do that of course

#

With it being against ToS and all

final iron
#

Mhm

wicked atlas
#

pretty sure they removed that kwarg too

opaque minnow
#

works fine for me

#

Anyone here well versed with python who thinks they could lend me a quick hand?

quick gust
#

just ask, this is the python server so there probably are people that can help :)

opaque minnow
#

I have several times haha no reply

slate swan
opaque minnow
slate swan
#

@novel apex

slate swan
opaque minnow
#

It's cool I'm sure someone would be able to help eventually ๐Ÿ™‚

boreal ravine
opaque minnow
# wicked atlas

Yeah but how would I filter it out? re.sub only accepts a string not an array

#

tried so many different things to filter out bad chars lol

#

The funny thing if I copy that filename and create it manually it works

#

just python can't handle it

solar anchor
#

how can i count the amount of roles on a server

#
@Bot.command()
async def serverstats(ctx):
    embed=discord.Embed(title=f"Server stats {ctx.guild.name}")
    embed.add_field(name="Users:", value=ctx.guild.member_count, inline=False)
    embed.add_field(name="Roles:", value=ctx.guild.role_count, inline=False)
    #embed.add_field(name="Channels:", value=len(ctx.guild.channels), inline=False)
    await ctx.send(embed=embed)```
slate swan
#

len(guild.roles)

solar anchor
#

ii tried this but ya lol

slate swan
solar anchor
#

it doesnt know guild

quick gust
#

because its ctx.guild.roles in your case

#

what he gave was not so that u can just copy and paste

hoary cargo
#

yaesmug why people don't use f strings

maiden fable
#

Lol

surreal sierra
#

hi, anyone knows why I get this problem?
this is the code


class main(commands.Cog):
    def init(self, Bot):
        self.bot = Bot

    def init(self, Bot):
        pass

    # Joins VC
    @commands.command()
    async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send(f"Please, may {ctx.author} join a voice channel for me to direct to!")

        voice_channel = ctx.author.voice.channel
        if ctx.voice_bot is None:
            await voice_channel.connect()
        else:
            await ctx.voice_bot.move_to(voice_channel)

def setup(bot):
    bot.add_cog(main(bot))
solar anchor
cold sonnet
solar anchor
surreal sierra
quick gust
solar anchor
quick gust
#

I'm guessing you removed len()

#

show what u did

solar anchor
surreal sierra
maiden fable
solar anchor
#

i think i can fix myself

quick gust
surreal sierra
quick gust
#

okay cool

solar anchor
maiden fable
#

@surreal sierra u wanna check if the bot is there in a voice channel?

surreal sierra
maiden fable
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
solar anchor
#

fixed it

quick gust
#

๐Ÿ‘

solar anchor
#

thnx for the help guys

maiden fable
#

@slate swan what was that attr, something like bot.voice.channel no? I forgot the attr

surreal sierra
slate swan
maiden fable
#

Oh, hmmm

slate swan
#

Guild.voice_client and Context.voice_client works too

maiden fable
#

Ah yea

#

ctx.voice_client

#

Wait, can we get the voice protocol of a member?

slate swan
#

probably not

maiden fable
#

Yea that's sad

wicked atlas
slate swan
#

RimuruSmug i never imagined using decorators for command arguments but now im doing it

maiden fable
#

Wym

slate swan
# maiden fable Wym

hikari things , they implemented prefix and slash commands together , and the arguments are accessed with Context.options.<argname>

#

for hikari-lb

#
@info_plugin.command
@add_cooldown(10, 2, bucket=UserBucket)
@option(
    name="emoji",
    description="Emojo to get information about",
    type=Emoji,
    required=True,
)
@command(name="emoji", description="Infor about an Custom Emoji", aliases=["emojiinfo"])
@implements(PrefixCommand, SlashCommand)
async def emoji_info_cmd(ctx: Context):```
![pepe_feelinglow](https://cdn.discordapp.com/emojis/729769345844248688.webp?size=128 "pepe_feelinglow")
#

but it kinda makes life easier by allowing prefix and slash command implements in the same function

maiden fable
#

Wait whaaa

#

But good implementation tho

#

BTW why can't u add args by adding them in function?? It's just sooo easier and readable

slate swan
#

also , the plugins ( yes , the cogs in hikari-lightbulb ) are too easy

quick gust
#

can I say that hikari is sexy

maiden fable
#

Why

slow fog
#

Ass

slate swan
#

slash commands have optional args , so it would have been hard to add it along with prefix ones

spring flax
#

If the bot is only on two guilds, would there be cache issues on bot.get_guild andguild.get_member?

spring flax
#

Meaning will they ever return None

spring flax
slate swan
maiden fable
#

@spring flax cache never depends on the number of guilds, be it 2 or 200. It will be cached the same way always

spring flax
slate swan
#

if you have member intents , yes

maiden fable
#

Well I don't really know about "always", but in most of the cases, provide the time and circumstances are normal, it should not return None

slate swan
#

and the ID Needs to be correct

maiden fable
#

And by normal, I mean stuff like correct ID (yes Sarthak), not having a connection issue and providing the bot with enough resources to run on

spring flax
#

it's for a modmail bot, so it's an on_message in DM's.

guild = bot.get_guild(ID)
guild.get_member(message.author.id)
#

But I prefer it working hundred percent of the time

maiden fable
#

BTW why u making your own modmail? Just saying, that it's already on GitHub, the original bot

spring flax
#

you mean this server's modmail?

#

or chambur's

maiden fable
#

Yea...

#

Both

#

The original one, made for entire discord, and this server's

#

Wait I ain't sure about @novel apex

spring flax
#

what's the original one?

#

the one by kyb3r?

maiden fable
#

Idk, I'm also confused now

#

There are soo many imposters

#

This is the original bot, according to me

spring flax
#

is that true?

maiden fable
#

Idk, I never hosted it

#

But I don't think there should be any issue

#

Since u r a Python Intermediate-Professional, and not a beginner or smth

spring flax
#

wait were you telling to use them or to fork and make my own version

slate swan
#

the original one

pliant gulch
#

You can tell by the dates the licenses were commit as well

#

Kyb3r first started the project in 2017 and chamburr started in 2019

spring flax
#

honestly I find those bots too complicated

#

I mean I just need it for one server

#

And there are so many lines of code and files in Kyb3r's

ripe ibex
#

This is probably for of a python question rather than a discordpy one, but here it is.

I am sending an embed like this. EmCons.py is the name of the file where I'm storing embed constants. Talker is the function I've made to return the embed.

await channel.send(embed=EmCons.Talker(ctx.author.id ,message)) #How I'm calling it
def Talker(intman:int , message):
    return Embed(title=f"Message from {hex(intman)[2:]}: ", description=f"{message}", color=0xff69b4)

This is the function in the EmCons file. This gives me the error

Command raised an exception: TypeError: Talker() takes 1 positional argument but 2 were given

The same code worked fine when I only had message as an argument. Not sure where I'm going wrong.

maiden fable
quaint epoch
#

is there an event for error handling in the on_message event?

prime inlet
#

im tryna run my bot but this keeps coming up, any ideas on what the problem is?

quaint epoch
#

like on_message_error or smth?

prime inlet
#

oh

twin moon
#
@nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
    async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
        submission = await reddit.submission(id = self.post.id)
        nl = "\n"
        comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
        for comment in submission.comments:
            if len(comments) < 4096:
                comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
        embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
        await interaction.response.send_message(embed = embed,view = Delete_View())```In data.embeds.0.description: Must be 4096 or fewer in length.
quaint epoch
#

client = discord.Client()

prime inlet
#

thx

#

im an idiot

quaint epoch
#

it's fine

#

although it's better to use discord.ext.command.Bot instead of client

#

but it's your choice

native wedge
prime inlet
twin moon
#

then

class cmd(commands.Cog):```
native wedge
prime inlet
native wedge
prime inlet
#

ok

rough wadi
prime inlet
rough wadi
#

Kk

final iron
#

So I changed my system to always have my database open

#

Now what?

#

Do I need to change anything else?

maiden fable
#

Damn my bot is in a server with 1k people ๐Ÿ˜ฌ

#

And it just joined it

prime inlet
#

nice

final iron
#

Also, do I need to like refresh it or smth

maiden fable
#

Oh hi there link

final iron
#

Aight

#

Time to refactor my 60 commands

maiden fable
#

Yay

static lintel
maiden fable
#

But then, it's just one single line of code

maiden fable
static lintel
#

so one of the solutions you gave me did end up working but I had typed it in wrong initially. turns out that doing pip3 install โ€˜DiscordUtils[voice]โ€™ worked but it needed to be exactly like that since I was on a mac so it was using a zch shell

maiden fable
#

Wait, what were u writing then?

#

If u weren't writing that

static lintel
#

I think I had dropped the single quotes and did pip instead of pip3

#

but seriously man I have to thank you for working so hard to try and solve my problem. Genuinely appreciate it very much

maiden fable
#

Weird... Nothing like that on Windows

maiden fable
static lintel
#

yeah this chat and all itโ€™s help is amazing

maiden fable
#

Agreed

slate swan
#

deadass looks like OpenDyslexic

twin moon
#
@nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
    async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
        submission = await reddit.submission(id = self.post.id)
        nl = "\n"
        comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
        for comment in submission.comments:
            if len(comments + f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}") >= 4093:
                comments += "..."
            else:
                comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
        embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
        await interaction.response.send_message(embed = embed,view = Delete_View())```In data.embeds.0.description: Must be 4096 or fewer in length.
maiden fable
maiden fable
#

SpookyNight @slate swan

twin moon
slate swan
#

trim your description to an adequate size

#

and provide a link to the comment instead

maiden fable
#

yea

slate swan
#

that way it's a "preview"

maiden fable
#

also please don't shout, thanks

slate swan
twin moon
# slate swan that way it's a "preview"
class Reddit_View(nextcord.ui.View):
    def __init__(self,post):
        super().__init__()
        self.post = post
    
    @nextcord.ui.button(label="Comments",style=nextcord.ButtonStyle.green)
    async def comments(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
        submission = await reddit.submission(id = self.post.id)
        nl = "\n"
        comments = f"**[{submission.title}]({reddit.config.reddit_url + submission.permalink})**{nl}{nl}"
        for comment in submission.comments:
            if len(comments) < 4096:
                comments += f"[{comment.author}]({reddit.config.reddit_url + comment.permalink}): {comment.body}{nl}{nl}"
        while len(comments) >= 4093:
            comments = comments[:-1]
            if len(comments) == 4093:
                comments += "..."
        embed = nextcord.Embed(title="",description = comments,colour = interaction.user.colour)
        await interaction.response.send_message(embed = embed,view = Delete_View())

    @nextcord.ui.button(label="๐Ÿšฎ",style=nextcord.ButtonStyle.blurple)
    async def close(self,button:nextcord.ui.Button,interaction:nextcord.Interaction):
        await interaction.message.delete()``` This worked but at the end gave me [dashda](somelink...
#

and not

#

@slate swan

slate swan
#

ow that hurts

#

please delete that message and use our pasting website

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

subtle frigate
#

what should I write so that it also calculates compound interest

maiden fable
#

Also would be better to use the math lib

#

!d math

unkempt canyonBOT
#

This module provides access to the mathematical functions defined by the C standard.

These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which donโ€™t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.

subtle frigate
#

ok

maiden fable
#

we told u

slate swan
#

he's already using it tho

#

he used math.sqrt

maiden fable
#

Oh mb

#

Didn't see

slate swan
#

seems like a bit of a big problem to solve here

slate swan
#

let's break it down:

#

CI = P( 1 + r/100)n - P

#

P = the amount we start with