#discord-bots

1 messages ยท Page 601 of 1

near sail
#

member.roles returns a list of roles

#

!d discord.Member.roles

full valley
#

oh

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ€˜@everyone](mailto:'%40everyone)โ€™ role.

These roles are sorted by their position in the role hierarchy.
dusk pumice
#

Tnx

#

๐Ÿ™‚

full valley
#

@near sail Do you know where I can find documentation on buttons

full valley
#

Yeah

near sail
full valley
#

Yeah well I was on there

near sail
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
full valley
#

tyvm

spice yoke
#

Now that discord.py is gone, which Discord API wrapper should I use in Python?

summer flume
#

what do u mean by gone?

slate swan
#

It's not gone, you can still use it perfectly fine

#

It just won't get updates for new features

#

And there are multiple forks or completely different libraries available I guess, I wouldn't recommend to use a fork though.

summer flume
#

๐Ÿ˜ฆ

dusky pine
#

hello everyone, does anyone know a good maintained fork of discord.py?

#

oh nevermind

#

someone else asked

placid skiff
#

How i can easily check if a text channel given by input from a command is a text channel?

spring verge
#

I wanted to ask if anyone is interested to learn hikari-lightbulb together..this way we can solve each other's doubts and learn more about developing discord bots...

shadow wraith
#

i just figured out how to make a slash command using the discord_slash module

#

dm me if you need a basic slash command example

#

will stop answering within like 5 mins

tawdry perch
shadow wraith
#

steps to make a dumba freaking slash commands

#
  1. go to discord.com/developers go to your bot go to oauth2 kick your bot from the server and then in the bot scopes select bot and application.commands and then reauthorize it back into the server
  2. do pip3 install discord_slash or pip install discord_slash
#
  1. go into your bot code and slap import discord_slash and from discord_slash import SlashCommand
slate swan
#

pin this

placid skiff
shadow wraith
slate swan
#

returns a boolean

tawdry perch
spring verge
spice yoke
#

why Hikari?

shadow wraith
#
  1. go for a cycle and do @slash.slash(name='name', description='description here')
    below that piece of sh- do async def name(ctx):
    below that crap indent your damn code and then just do await ctx.send('your mom')
slate swan
spice yoke
#

I think Nextcord looks nice

slate swan
spice yoke
spring verge
slate swan
#

Hikari is better because it's a separate library

shadow wraith
#

ye thats the steps you need to make a slash command

spring verge
shadow wraith
#

if its similar who cares :trol:

spice yoke
placid skiff
spice yoke
#

you know what

#

nextcord is easier for me as i've made a discord.py bot before, but I think i'll jump right into hikari just for that static typing

spring verge
shadow wraith
#

speaking of static typing, how in the world do you get a bot to do typing for how much time you want and then send the message

spring verge
shadow wraith
slate swan
#
@bot.command()
async def longCommand(ctx):
   async with ctx.typing():
        await sleep(10)
   await ctx.send("Done!")
#

just sleep

shadow wraith
#

freaking jenius

#

use time.sleep i see i see

#

@slate swan i got an error ๐Ÿ’€

#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 
'await' expression```
`
#

oh wait

#

i see whats wrong srry you dont use await i think

placid skiff
#

How to create a Task inside a cog?

slate swan
shadow wraith
slate swan
#

you can if it supports async

slate swan
brittle jay
#

Hi.
I'm making a discord bot, and I want to know if a bot has the higher role than a specified member.
I see something like discord.User.top_role but I don't know how to use it. Anyone can help? Thank you!

boreal ravine
visual island
#

you get the Member object then compare it like if guild.me.top_role > Member.top_role:

boreal ravine
#

why user tf

visual island
#

oops

brittle jay
#

Oh thanks

boreal ravine
#

dont come back and ask how to get the member object kthx

rare saddle
#

Guys, how to make the author the correct condition if the id is in this collection, well, there I use this check

placid skiff
#

guys I need to use a converter but i don't have a context, what can I do?

rare saddle
#

1.7.3

boreal ravine
#

why

#

do you need

slate swan
#

oh so you use discord-components for button , in the check right?

placid skiff
#

btw i find another way

slate swan
placid skiff
#

but I have now to send an img from an url

slate swan
#

its correct

boreal ravine
placid skiff
#

i need the channel into a tasks loop

boreal ravine
#

Ah

placid skiff
#

so i don't have a context

boreal ravine
placid skiff
#

nope, it is not a command, is a tasks loop

slate swan
#

you can make a custom context

placid skiff
#

how?

rare saddle
boreal ravine
placid skiff
#

By the way i have to send an image from a url (just a send message, not embed), how I do that?

rare saddle
boreal ravine
#

discord will embed it

placid skiff
#

i didn't wish to show the url :L

slate swan
#

maybe try getting all the members and use it

#

i dont use mongodb , so exactly dont remember it , its something like find_all if im not wrong

arctic vapor
#

AttributeError: 'NoneType' object has no attribute 'get_member'
im getting this error, code is

  @commands.Cog.listener()
    async def on_message(self, message):
       x = message.guild.get_member(118470023181369344) or await message.guild.fetch_member(118470023181369344)

        if x in message.mentions:
            em = discord.Embed(description  = f"{message.content}",color = discord.Color.blue())
            em.set_author(name=message.author, icon_url=message.author.avatar_url)
            em.set_footer(text= message.created_at)
            if message.attachments:
                em.set_image(url = message.attachments[0].url)
            await message.channel.send(embed = em)

i cant see what im missin

slate swan
slate swan
placid skiff
#

Like save one message into the database from that guild id

slate swan
#

you just need a text channel object right?

arctic vapor
slate swan
#

have your turned off guild intents?

rare saddle
#

I did like this, but it still doesn't work

slate swan
placid skiff
arctic vapor
#

nope, all intents are on, but ye i removed the line where it sends a message to the user and its fine

#

thanks

slate swan
slate swan
placid skiff
#

it depends on the administrator of that server, they can change it, but it will be saved in the database by the way

rare saddle
placid skiff
#

So i don't need that the context is the same channel, i just need a context object

slate swan
placid skiff
#

yes, but i get the id of the channel

#

which is not a channel object by itself

slate swan
slate swan
#

it will give u the channel object

placid skiff
slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
placid skiff
#

bruh hahaha

#

thanks

slate swan
#

basically , channel = bot.get_channel(id)

#

np

sick talon
#

how can I find the number of users connected in the voice channel

maiden fable
unkempt canyonBOT
boreal ravine
#

hm

slate swan
#

use random.randint and some logic

#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
slate swan
#
@rm.event
async def on_member_join(member):
        channel = rm.get_channel(910432929216344105)
        embed = i defined embed here
        await channel.send(embed=embed)```
#

it just won't send the welcome embed

#

no error printed

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

Enable the members intent

slate swan
#

what's rm

#

is it your bot?

#

yea

#

in that case

#

either you gave a wrong ID

#

or the bot doesn't see the channel

#

in get_channel()

#

umm that id is valid and the bot can see the channel too

#

send the whole error then

#

in copy paste

#

with more traceback...

steep estuary
#

how i can get my total commands ?

slate swan
#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
#

property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
steep estuary
#

i use this

#

by len(bot.all_commands.keys())

#

but this also include aliases

slate swan
#

mhm

steep estuary
#

of commands i don't want them

slate swan
#

why all_

slate swan
steep estuary
#

bot.commands ??

slate swan
#

yes

steep estuary
#

ok :/

slate swan
#

well what do you exactly want

#

just the name?

#

of the commands

#

or the description too?

steep estuary
#

no

#

my bot show this the len of commands but when i add aliases in any command it add that also in the length

slate swan
#

so why do you use .keys

steep estuary
#

ohk

#

let me try :/

slate swan
#

tho funny number

steep estuary
#

how to get any user's pings ?

maiden fable
unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

maiden fable
#

!d discord.Member.mentioned_in

unkempt canyonBOT
steep estuary
#

?

#

no

maiden fable
#

Then?

steep estuary
#

i mean pings means network

#

?ping

maiden fable
#

Not possible

#

You can't access someone's latency

steep estuary
maiden fable
#

Can I see an example?

steep estuary
#

ok

sage otter
#

You serious right now?

steep estuary
#

idk what it show

maiden fable
#

๐Ÿ˜

sage otter
#

Thatโ€™s not your ping. Thats the bots ping.

maiden fable
unkempt canyonBOT
#

property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
steep estuary
#

but it shows different of each user

steep estuary
maiden fable
#

Smh

sage otter
#

Because ping wonโ€™t always be consistent

steep estuary
#

but when my friend did

#

it was showing something near 1000

maiden fable
#

Hmm

steep estuary
#

:/

maiden fable
#

It's totally a discord thing

#

Not a user latency

steep estuary
#

ok

maiden fable
#

!d discord.Client.latency is what they use

unkempt canyonBOT
#

property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
dusk pumice
#

How can I get role ids?

#

I need to get role ids that user have

#

Anyone?

sage otter
#

[r.id for r in Member.roles]

#

List comprehension is beautiful isnโ€™t it.

dusk pumice
#

Agree ๐Ÿ™‚

#

Thank you.

slate swan
#
            pages = 2
            cur_page = 1
#embed stuff
            message = await ctx.send(embed=emb)

            await message.add_reaction("โ—€๏ธ")
            await message.add_reaction("โ–ถ๏ธ")

            def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in ["โ—€๏ธ", "โ–ถ๏ธ"]

            while True:
                try:
                    reaction, user = await self.bot.wait_for("reaction_add", timeout=5 check=check)
                    if str(reaction.emoji) == "โ–ถ๏ธ" and cur_page != pages:
                        cur_page += 1
                        await message.edit(embed=embed1)
                        await message.remove_reaction(reaction, user)

                    elif str(reaction.emoji) == "โ—€๏ธ" and cur_page > 1:
                        cur_page -= 1
                        await message.edit(embed=emb)
                        await message.remove_reaction(reaction, user)

                    else:
                        await message.remove_reaction(reaction, user)

                except:
                    pass```
maiden fable
dusk pumice
#

XD

maiden fable
slate swan
#

yeah i did that

#

ill test

slate swan
maiden fable
#

Code

slate swan
maiden fable
#

Weird

slate swan
#

ima restart the bot and try agian

#

yep, same thing @maiden fable

brittle ingot
#

still happening?

maiden fable
brittle ingot
#

i think it has to do with the curpage portion of each if/elif. Whenever i did wait_for's with reactions that was always my issue :/ idk why

slate swan
#

so what do you recommend

maiden fable
#

About What

slate swan
#

what should i do instead

#

or shall i just lower the timeout

maiden fable
#

You really can't do anything...

maiden fable
brittle ingot
#
@bot.command()
async def myMenu(ctx):
    totalPages = 2
    curpage = 1

    embed = discord.Embed(title="Number 1")
    emb = discord.Embed(title="Number 2")
    
    msg = await ctx.send(embed = embed)
    emojis = ["emoji1", "emoji2"]
    for emoji in emojis:
        await msg.add_reaction(emoji)

    def check(reaction, user):
        return user !== user.bot and reaction.message.id == msg.id and str(reaction.emoji) in emojis

    while True:
        try:
            reaction, user = await self.bot.wait_for("reaction_add", check = check, timeout = 60)

        if str(reaction.emoji) == "emoji1":
            if curpage > totalPages:
                await msg.remove_reaction(reaction, user)
            elif curpage < totalPages:
                await msg.edit(embed = emb)
                await msg.remove_reaction(reaction, user)
                curpage += 1

............ etc
#

is how i did it.

boreal ravine
brittle ingot
#

you still need to use a wait for. i mean they look cleaner, idk about easier though. I also haven't used them since discord_components first came out

brittle ingot
maiden fable
#

Ah, okay

sage otter
boreal ravine
boreal ravine
sage otter
#

Does he ever break out of his while loop.

maiden fable
brittle ingot
brittle ingot
#

well that's not totally true. I do maintenance on existing bots.

boreal ravine
#

I personally started using dpy in june/july when my school had a 2 month break ๐Ÿ˜Ž

brittle ingot
#

nice.

sage otter
brittle ingot
#

idk how to explain why you put it in a while loop (just woke up here) but its what you are supposed to do...

sage otter
#

Yeah but he never breaks out of.

#

Thatโ€™s why time outs arenโ€™t working

brittle ingot
#

ahh

sage otter
#

It will continue the bot.wait_for()

#

Over and over and over

brittle ingot
#

so should add a break in the asyncio.timeout portion of the except?

sage otter
#

Honestly

#

Id just add like an โŒ reaction to the message and when they click that it breaks out

brittle ingot
#

yeah that is what i would usually do and have it delete the message before breaking.

sage otter
#

Mhm

dusk pumice
#

How to ping roles that user have?

#

Does anyone knows it

#

please...

sage otter
#

Consider

#

!d discord.Role.mention

unkempt canyonBOT
dusk pumice
#

...

#

Notthat

brittle ingot
#

you access the members roles with member.roles and iterate through that and run role.mention on it to get the "ping"

#

so yes, yes that

dusk pumice
#

Hmm

sage otter
#

[r.mention for r in Member.roles]

dusk pumice
#

I want like this

sage otter
#

And join that somewhere ig

brittle ingot
boreal ravine
#

๐Ÿ˜Œ

flint isle
#

I am needing code to copy a image from a message

slate swan
#

We don't code for you

#

!d discord.Message.attachments

unkempt canyonBOT
slate swan
#

Contains the list of images in a message

flint isle
#

Ok thanks I will look at that

flint isle
slate swan
#
print(ctx.message.attachments)
#

ยฏ_(ใƒ„)_/ยฏ

#

Returns a list of all images

#

Then use a loop to get each image individually (basic Python loop)

#

so

#

we added reaction pages on shop

dusk pumice
boreal ravine
#

or whatever ur doing

#

!d discord.Client.wait_for usr this

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

slate swan
normal folio
slate swan
#

this happens everytime u do !startbattle

#

its a command to dm people

slate swan
normal folio
sage otter
flint isle
sage otter
#

Caps matter

slate swan
#

anyone here use discordrb?

full valley
#

Anyone know how to use discord buttons as commands?

maiden fable
unkempt canyonBOT
slate swan
#

How to stop local ratelimits?

maiden fable
flint isle
sage otter
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

Use the f-strings

maiden fable
slate swan
#

He's sending "ctx.message.attachments" instead of using f-strings correctly

slate swan
#

oh my bad

maiden fable
#

Lol

slate swan
#

LOL

#

forgot this is a py only server

#

How to stop local ratelimits?

slate swan
flint isle
sage otter
#

Tbh if thatโ€™s all heโ€™s putting. He doesnโ€™t even need to f string it. Just pass it in as is.

#

Pretty sure thereโ€™s automatic string casting.

slate swan
sage otter
slate swan
#

example plz

#

There is an example on the documentation

#

!d discord.ext.commands.Bot.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**...
slate swan
#

See by yourself

sage otter
slate swan
#

It just gives a list of Attachment objects

#

Loop through it as I already said

#

And use the .url attribute to get the URL of the attachment

sage otter
flint isle
slate swan
#

Just said above

sage otter
#

[i.url for i in Message.attachments]

slate swan
#

Make a loop and get the .url attribute

full valley
#

Finding it so hard to learn how to use buttons

#

all videos are just old packages for d.py 1.0

slate swan
#

plus it says this is not being used

#

thats what the green line mean

flint isle
sage otter
#

By joining it

#

!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'
flint isle
sage otter
#

come on man, this is really really simple :/

slate swan
boreal ravine
slate swan
#

In case you can't filter what information you need to care about

maiden fable
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'
maiden fable
#

Idk if that's what u got the ss from, but who cares

slate swan
#

Exactly from the embed that got already sent and that you sent again for no reason

#

And as I said

#

In case you can't filter what information you need to care about

full valley
#

Anyone know how to create commands out of buttons, or where I can find info on buttons

#

kind of going crazy here YEP

flint isle
#

!seperate

slate swan
flint isle
#

!split

slate swan
#

wait ill show an example

#

!e py string = 'word1 word2 word3' print(string.split(' '))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

['word1', 'word2', 'word3']
ashen notch
slate swan
#

oh so i'd just append their ids to a list ?

maiden fable
slate swan
#

not sure what to exactly do

ashen notch
#

You're wanting to add the role to someone?

#

In that case there's a method to do that

slate swan
ashen notch
#

Ohhhhhhhhhhhhhhhhhhhhhh

#

Okay yeah, I getcha now

slate swan
ashen notch
#

So at least within @unkempt canyon

#

We end up storing those in a database, and check against it when people join

#

See if they had any relevant roles/infractions on them to reapply

slate swan
ashen notch
#

Sorry, I was lacking in the caffeine department

slate swan
#

i'm just trying to do it with one role and its not that big of a server , would a list be a good option ?

slate swan
ashen notch
#

Sort of. The problem is that if the bot goes down, that list does too, so you'd need some sort of persistence

slate swan
#

oh right

#

maybe before the bot goes down it would store that list in a json ?

#

on_bot_disconnect or something

ashen notch
#

That's assuming it doesn't crash

sage otter
#

Noโ€ฆ.

#

You donโ€™t use json for data storage

ashen notch
#

I'd recommend just using a little SQLite database

slate swan
#

ik how to use databases , but then whats the use of json ?

sage otter
#

States

ashen notch
#

JSON is for - yeah that

slate swan
#

states ?

ashen notch
#

It's typically for data transfer rather than storage

#

Like getting it back as a response from a web request

slate swan
ashen notch
#

If it's just for one server, that's a bit overkill

slate swan
#

why posgresql for a single role xd

#

yeah its only for one server

ashen notch
#

SQLite would be more than sufficient

slate swan
#

just use sqlite , aiosqlite if you want it to be asynchronus

sage otter
#

Then thereโ€™s no persistence

slate swan
ashen notch
#

Essentially the same

sage otter
#

Cache is flushed every time the program is terminated

slate swan
#

oh fair , i'd go with mysql then

ashen notch
#

It just puts it in a single file rather than connection to a server

slate swan
#

aiomysql lemon_thinking

sage otter
#

donโ€™t you need a server for mysql.

#

?

ashen notch
#

That's the main benefit of SQLite is that it's tiny and doesn't really require much setup at all

sage otter
#

^^^^

slate swan
#

it uses the same sql query right ?

ashen notch
#

Yeah. I think the only difference might be how it handles adding variables to the query, but the core SQL itself is the same

slate swan
#

almost , other than ? instead of %s

ashen notch
#

That

slate swan
#

oh cool cool

ashen notch
#

Thanks, I couldn't remember

slate swan
#

also uh just for the record how to make a list inside an init method

#
def __init__(self, bot,muted_people=[],last_user=None):
        self.bot = bot
        self.last_user = last_user
        self.muted_people = muted_people
    ``` like wise ?
ashen notch
#

No, that's a bit of a beginner's trap

#

So if you do that, if you end up using the default value, it'll be the same list for each instance

#

Rather than a fresh one

slate swan
#

ohh

#

so making it a class attribute is a better idea

ashen notch
#

Yeah, if you need it consistent across all instances.

#

But if you're potentially passing in an existing list, then you'd need to do it that way

#

I think

#

Difference is.... one sec, writing example

#
def mah_function(my_list=None):
  if my_list is None:
    self.my_list = []
  else:
    self.my_list = my_list
#

I mean that's a clunky example, but you get the idea

slate swan
#

i apply the same logic to the init method ?

ashen notch
#

Yarp

#

Otherwise you end up with....

slate swan
#

thanks hemlock , i really appreciate it

slate swan
ashen notch
#

!e

def ham(number, spam=[]):
  spam.append(number)
  print(spam)

ham(5)
ham(6)
unkempt canyonBOT
#

@ashen notch :white_check_mark: Your eval job has completed with return code 0.

001 | [5]
002 | [5, 6]
slate swan
#

oh that could be used aswell

#

smart

ashen notch
#

Could be, but it's really dirty

slate swan
#

yeah first one looks cleaner

ashen notch
#

And I think it's an implementation detail, so it shouldn't be relied on

slate swan
#

how do i use wait_for cuz i was trying to figure out

@bot.event
async def on_reaction_add(message, reaction, user):
    if message.content.startswith(',shop'):
      if user != bot.user:

        if str(reaction.emoji) == ':arrow_right:':
            em2 = discord.Embed(title = "Shop - Others", color = discord.Color.purple())
            await reaction.message.edit(embed=em2)

        if str(reaction.emoji) == ':arrow_left:':
            em = discord.Embed(title = "Shop - Tools", color = discord.Color.purple())
            await reaction.message.edit(embed=em))':thumbsup:')```
slate swan
hazy canopy
#

someone knows how to remove the help command that is on default in a discord bot?

sage otter
#

Bot.remove_command("help")

hazy canopy
#

ok thx

ashen notch
#

Ninja'd

slate swan
#

if you want the message you may use reaction.message

ashen notch
#

I think this example might help. Snagged it from the docs:

@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that ๐Ÿ‘ reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '๐Ÿ‘'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('๐Ÿ‘Ž')
        else:
            await channel.send('๐Ÿ‘')
``` https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.wait_for
#

I think it's what you need?

#

Not 100% sure, though

#

@slate swan Just to make sure you're seeing this

flint isle
#

!e

Url = ['https://cdn.discordapp.com/attachments/798726720181633047/910540678247882822/20211117_092059.jpg']
Separator = "'"
Print(separator.join(colors))```
slate swan
ashen notch
#

Ah, my mistake

#

You could make it part of the check, couldn't you?

slate swan
flint isle
#

!e

Url = ['https://cdn.discordapp.com/attachments/798726720181633047/910540678247882822/20211117_092059.jpg']
separator = "'"
print(separator.join(Url))```
slate swan
ashen notch
#

The example I listed is as well

slate swan
#
client.get_guild(672453244336734208)``` returns `None`
#

guild is not in the cache , the bot is not in the guild...

#

it is

#

if it is , make sure that you dont have your guild intents off ( its enabled by default tho)

#
    path = "./suggestions.json"
    amount_times = 1
    data = {}
    data[message.author.id]
    with open ("./suggestions.json","w") as file:
      json.dump(data, file, indent=4)```
#

may i see your intents

#

I'm trying to make it so everytime they send a message it opens the "suggestions" json file and adds another number to their ID in the json.

#

I'm still trying to learn, but basically I wanna do something like:

user_id: 1
user_id: 2
slate swan
#

can anyone help me with this?

slate swan
#

I know a database is easier but still trying to learn.

slate swan
slate swan
#
    path = "./suggestions.json"
    amount_times = 1
    data = {}
    data[message.author.id] = []
    with open ("./suggestions.json","w") as file:
      json.dump(data, file, indent=4)```
slate swan
slate swan
slate swan
#

I don't get how to add a number then append it by one for the user

normal folio
#

How to make it work only on specific command ,shop

slate swan
slate swan
slate swan
#

as the example hemlock sent

normal folio
slate swan
#

Wdum by empty list

slate swan
slate swan
#

what goes in it?

#

the value you want for the key?...

normal folio
# normal folio How to make it work only on specific command `,shop`
@bot.event
async def on_reaction_add(reaction, user):
    if user != bot.user:
        if str(reaction.emoji) == "โžก๏ธ":

            em2 = discord.Embed(title = "Shop - Others", color = discord.Color.purple())
            await reaction.message.edit(embed=em2)
        if str(reaction.emoji) == "โฌ…๏ธ":

            em = discord.Embed(title = "Shop - Tools", color = discord.Color.purple())
            await reaction.message.edit(embed=em)
``` also here is the code
slate swan
#

So whatever I put in it will go into the json?

#

ofcourse

#

I'm trying to dump this into json

#

user_id: <amount of times talked>

#

that's it

normal folio
slate swan
#

but idk how

slate swan
# slate swan but idk how
with open('the_json_file.json' , 'w') as file:
  data = {}
  data[str(message.author.id)] = #number of time the command was used
  json.dump(data , file)``` thats how json works

as for the how many times the user talked , you may keep on adding 1 to the value of data[str(message.author.id)] which would be a reading operation first , and then writing it
#

So what is data = {} doing?

#

That makes sense, but then how do you format it how you want.

#

data = {} is declaring an empty dictionary to be dumped inside the json

#

how can i fix a missing argument error?

#

oh

slate swan
#

But then how could you make the number not fixed?

slate swan
slate swan
slate swan
#

alr

#

I'm so confused..

slate swan
#

So I got it to dump my ID

#

and , mention someone when use the command

#

ohhh so i change it from member to discord.Member? alr

slate swan
#

alr alr

#

it works tysm

slate swan
slate swan
#

I think trying to do it this way won't work.

#

well , if you use sqlite3 , its much easier

#

So JSON is the old way?

#

But JSON is more useable when you don't wanna use a host.

shy schooner
#

mongodb is quite good, it's non-relational db

shy schooner
slate swan
#

No but you can use it as one lol

slate swan
flint isle
slate swan
flint isle
# slate swan i see , you can do `"\n".join(ctx.message.attachements)`

Error

loading embed cog
Ready!
whiskeythefox initiated boop command.
Ignoring exception in command cmd:
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "<string>", line 46, in boop
AttributeError: 'Message' object has no attribute 'attachements'

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

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'attachements'```
The code 
```py

@bot.command(name='cmd', description='boop someone', alias=['cmd1','cmd2'])
async def boop(ctx):
            print(f'{ctx.author.name} initiated boop command.')
            await ctx.send(f'{ctx.message.attachments}')
            await ctx.send( "\n".join(ctx.message.attachements))
            Url = [i.url for i in ctx.message.attachments]
            separator = " ' "
            print(separator.join(Url))
                        
            print(ctx.message.attachments)```
slate swan
#

wrong spelling sorry

#

attachments it should be

flint isle
#

Ok

#

I got this error after I fixed spelling

loading embed cog
Ready!
whiskeythefox initiated boop command.
Ignoring exception in command cmd:
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "<string>", line 46, in boop
TypeError: sequence item 0: expected str instance, Attachment found

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

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: sequence item 0: expected str instance, Attachment found```
slate swan
#

eh i see

#

you would have to iterate thru the attachments frst

#
list_urls = []
for atchm in ctx.message.attachments:
  list_urls.append(atchm.url)

await ctx.send( "\n".join(list_urls))
#

So

#

How do I check if the user is in the json?

#
if data[str(message.author.id)] not in list(data.keys()):```
#

Like this?

flint isle
#

Now I have to find how to make the bot wait for a reaction on a message

#

@slate swan ^ would you happen to know how to do that?

sage otter
#

!d discord.ext.commands.Bot.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**...
sage otter
#

List comprehension exist. And when he asked the same question earlier I already gave him the code he needed to join.

normal folio
#

doesn't respond to reactions

sage otter
#

He was literally just waiting for someone to spoonfeed him code on joining an iterable to a string even though we pulled up examples for him.

#discord-bots message

dusk dust
#

how to handle multiple reactions in this case?

    await form_recebido.add_reaction('๐ŸŸฉ')
    await form_recebido.add_reaction('โฌœ')
    await form_recebido.add_reaction('๐ŸŸฅ')

    def react1(reaction, user):
        return str(reaction.emoji) in "๐ŸŸฉ"
    
    def react2(reaction, user):
        return str(reaction.emoji) in "โฌœ"

    def react2(reaction, user):
        return str(reaction.emoji) in "๐ŸŸฅ"

    await bot.wait_for("reaction_add", check=react1)
    await autor.send('accepted')
    await bot.wait_for("reaction_add", check=react2)
    await autor.send('to analyze')
    await bot.wait_for("reaction_add", check=react3)
    await autor.send('denied')
slate swan
#

do one wait_for

#

the check should pass when the reaction is any of those

#

then you can check which reaction it was with if statements

dusk dust
#

and, would the "if" look like this?

if reaction.emoji == '๐ŸŸฉ':
        await autor.send('accepted')
slate swan
#

exactly

#

wait

#

you forgot to convert the emoji

#

str()

patent surge
#

d!client

slate swan
#

How do I check if a user has a role outside of cogs? It's in on_message

patent surge
#

!dclient

slate swan
#

#bot-commands

patent surge
#

!d client

dusk dust
slate swan
#
  @commands.Cog.listener()
  async def on_message(self, message): 
    if not syst.isMod(self.message, message.author): return   ```
slate swan
#

well a lot of things are different in cogs

dusk dust
slate swan
#

@commands.Cog.listener() is @botObject.listen()
events/commands outside of cogs don't take self
syst may not be defined

slate swan
#

I don't have no information about that

slate swan
# slate swan well um
    role = guildObject.get_role(892863132299587595)
    if role in message.author.roles:```
#

Doesn't work says guildObject isn't defined

#

why do you think

#

you have to replace it with what the name says

#

a guild object

#

idk

#

message.guild probably

#

hey

#

got it working ๐Ÿ˜ฎ

dusk dust
# slate swan I don't have no information about that
    autor = ctx.author

    await form.add_reaction('๐ŸŸฉ')
    await form.add_reaction('โฌœ')
    await form.add_reaction('๐ŸŸฅ')

    def react(reaction, user):
        return str(reaction) == '๐ŸŸฉ'

    def react(reaction, user):
        return str(reaction) == 'โฌœ'

    def react(reaction, user):
        return str(reaction) == '๐ŸŸฅ'

    await bot.wait_for("reaction_add", check=react)
    if reaction.emoji == str('๐ŸŸฉ'):
        await autor.send('txt1')

    if reaction.emoji == str('โฌœ'):
        await autor.send('txt2')

    if reaction.emoji == str('๐ŸŸฅ'):
        await autor.send('txt3')
```  It was like this
slate swan
#

nice job @slate swan

#

well um

#

no, that's not it

#
def react(reaction, user):
        return str(reaction) == ':green_square:' or str(reaction) == ':green_square:' ...```
#

one check would make it

#

with this formula

dusk dust
#

ok

slate swan
#

so redefining a function doesn't do anything

#

just the last one would be how it's defined

#

the first 2 are just memory wastes

#

and I have to correct myself

#
def react(reaction, user):
        return str(reaction.emoji) == ':green_square:' or str(reaction.emoji) == ':green_square:' ...```
#
if str(reaction.emoji) == '๐ŸŸฉ':
#

can someone help me with this error?

#

not without code

#

this is the code i wrote

slate swan
#

first of all, while True will block everything else in your code

#

so i remove it

#

you should make a task

#

google it

#

but the main problem is that get() didn't find the role

#

ohhhh

#

in the server i dont have any roles

#

that might be the problem

#

lmao

#

-Computer, find this for me. Hint: it don't exist
-ok

#

:)

jovial plover
#

discord.utils.get(ctx.guild.roles, name="everyone")
Is this possible?

slate swan
#

!d discord.Guild.default_role

unkempt canyonBOT
slate swan
#

but it would

#

just makes no sense to use it

slate swan
#

Hi, is there a way to get the members avatar without the url? Like I don't get a url but a file

#

in 2.0

#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
slate swan
#

or maybe not just in 2.0

#

cuz the api reference doesn't mention it

slate swan
#

you might have to

#

I'm not certain

#

oh kk i see

#

because the API reference doesn't explicitly mention it

#

So in a on_member_join - event this should work?

pfp = member.User.avatar
#

why the User

#

so just member_avatar?

#

discord.Member.avatar

#

.

#

where discord.Member is replaced with an instance of it

#

so just member.avatar

#

ok ty

#

Well uhh now I get this output: c931c5ef1b7a77fcb19138b84b81fd0d @slate swan

jovial plover
#

target=discord.utils.get(ctx.guild.roles, name="everyone")
How can i make this work based on names?

I get this error : raise InvalidArgument('target parameter must be either Member or Role')

slate swan
#

Can you somehow check if channel_id can be sent a message?

#

no slowmdoe or anything

slate swan
#

told u it's not worth it

#

use ctx.guild.default_role

jovial plover
#

what about other roles?

slate swan
#

wdym

jovial plover
#

other than default

slate swan
#

don't you wanna get @everyone

jovial plover
#

Asking in general

slate swan
#

it's not a string

#

maybe save it

#

that's probably what save does

slate swan
#

hmm?

#

did you try to resize an object, that was defined by the library, with a built-in function?

#

!d discord.Asset.save

unkempt canyonBOT
#

await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Saves this asset into a file-like object.
slate swan
#

assign this to a variable

#

pfp = member.avatar.save()

#

with my logic, it should work and be resizeable

#

it could definitely be wrong :bruhkitty:

#

Let me try

#

Well now it says:

AttributeError: 'str' object has no attribute 'save'```
#

xdd

#

bro wat

#

it can't return a string

#

Bru I'm just trying to do a welcome message with image manipulation is it that complicated xddd

slate swan
#

that would be the only explanation

#

@slate swan To install the new version. Do I just have to do pip install discord.py -- upgrade

#

or smth like that

#

no

#

you need a github url

#

pip install -U github_url

#

which I currently can't find

#

i see

jovial plover
#

how to get id of the role with just it's name

slate swan
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
slate swan
#

iterable is your guild

#

**attrs is the name

#

with name="name"

lyric moat
#

why when i run

python --version```

It says 
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
slate swan
lyric moat
#

In command prompt btw

#

kk ty

jovial plover
#

is it possible to get a bot's invite link

slate swan
#

only from the dev portal

maiden fable
#

No?

#

Lol just get the bot ID and the permission integer and u can make the invite link yourself

slate swan
#

what the

maiden fable
#

Yea

#

Lemme show u

vapid python
#

hello

maiden fable
#

@slate swan

slate swan
#

omg actually

maiden fable
#

Hahaha

#

That is how I am making the invite link

#

I ain't hardcoding it but getting the bot's ID

slate swan
#

should I try to invite this modmail to my server

#

but it ends with bot for me

maiden fable
#

Lol won't work

#

Private Bot

slate swan
#

don't matter

#

I invited another one

#

prankman

maiden fable
lyric moat
slate swan
#

@slate swan Okay Bro got it now. But I have to save it as a png file to send it. Is there a way it auto-deletes itself after 10 secs or so? Because if don't my whole server will be full of those welcome images xddd

#

you mean that the message deletes itself?

sullen shoal
#

send has a delete_after kwarg

slate swan
sullen shoal
#

it accepts seconds as float

slate swan
#

In my folder

#

!d os.remove

unkempt canyonBOT
#

os.remove(path, *, dir_fd=None)```
Remove (delete) the file *path*. If *path* is a directory, an [`IsADirectoryError`](https://docs.python.org/3/library/exceptions.html#IsADirectoryError "IsADirectoryError") is raised. Use [`rmdir()`](https://docs.python.org/3/library/os.html#os.rmdir "os.rmdir") to remove directories. If the file does not exist, a [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "FileNotFoundError") is raised.

This function can support [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd).

On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

This function is semantically identical to [`unlink()`](https://docs.python.org/3/library/os.html#os.unlink "os.unlink").

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.remove` with arguments `path`, `dir_fd`.

New in version 3.3: The *dir\_fd* argument...
slate swan
#

you give in the path

sullen shoal
#

the guy literally linked the docs above you

slate swan
#

yep, it has many informations since it's really official lmao

summer gazelle
#

Hey, is there a way to refresh a message in every x minutes/seconds using backgroundtask?

sullen shoal
#

refresh a message?

summer gazelle
#

Yep

#

I'll give you an example

#

In staff list channel, I want to refresh that list every day so when new staffs joins the staff team, there are being listed in the list

#

So it should be refreshed to give you the correct number of staffs

#

Like the stats bot he refresh the number of members

#

I want to do that in a channel with an embed for exemple that is being refreshed

sullen shoal
#

!d discord.abc.Messageable.fetch_message

unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
summer gazelle
#

How?

sullen shoal
#

I havent done it before so im not sure

#

however, i assume your bot will stay online most of the time,
you can simply store the message object as a variable and use it and if your bot goes offline, you may somehow indicate to fetch it again

summer gazelle
#

My bot is hosted 24/7 so no worries

sullen shoal
#

so you can just store it as a variable as pass it, and if your bot goes offline, fetch it once and store it again

#

otherwise I think you can use the pickle built-in module

#

to store it to a file and load the object

untold token
#

dpy asynchronous tasks

rare saddle
#

How to make a condition that if the author has no roles then

cerulean osprey
#

Why is my bot going offline a lot 2DSad

brisk helm
#
                join = "".join(x)
                await ctx.send(f"```odbanowano {join}```")``` how to send it as file??
sullen shoal
cerulean osprey
sullen shoal
unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ€˜@everyone](mailto:'%40everyone)โ€™ role.

These roles are sorted by their position in the role hierarchy.
rare saddle
cerulean osprey
sullen shoal
#

at least read the docs

cerulean osprey
full lily
slate swan
#

How can I make this black Background transparent?

sullen shoal
#

which image library are you using

#

or is it someone's profile picture?

slate swan
#

@sullen shoal It is someones pfp i'm using PIL

sullen shoal
#

so their pfp is by default transparent or you rounded it

slate swan
# sullen shoal so their pfp is by default transparent or you rounded it

I rounded it by doing this:

def circle(pfp,size = (215,215)):
    
    pfp = pfp.resize(size, Image.ANTIALIAS).convert("RGBA")
    
    bigsize = (pfp.size[0] * 3, pfp.size[1] * 3)
    mask = Image.new('L', bigsize, 0)
    draw = ImageDraw.Draw(mask) 
    draw.ellipse((0, 0) + bigsize, fill=255)
    mask = mask.resize(pfp.size, Image.ANTIALIAS)
    mask = ImageChops.darker(mask, pfp.split()[-1])
    pfp.putalpha(mask)
    return pfp

Idk if it's good or not, copied it from Github

#

you can also directly insert the alpha channel into the image using numpy

full valley
#

Hi, how can I call a bot command from inside another bot command

sullen shoal
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
full valley
#

so I dont need get_command?

sullen shoal
#

you need it

#

you have to pass the Command to it

full valley
#

so what would the syntax be?

#

I'm a little confused

sullen shoal
#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
sullen shoal
#

it would be something like,

full valley
#
await ctx.invoke(bot.get_command('queue')
sullen shoal
#

yes

full valley
sullen shoal
#

ctx stands for Context

full valley
#

yes

#

why is it not in the example

sullen shoal
#

when you use the decorator to add a command,
the lib will pass the Context as the the first argument.
You can call it whatever you want

#
async def my_command(context):
  await context.send('hello world')
brisk helm
#

How to reply with out ping?

sage otter
#

mention=False

#

await ctx.reply(content="โ€ฆ", mention=False)

quiet coral
safe depot
#

Hey, im working on a purge command and im having some trouble with it, i want it to work of roles and not permissions, ive got it work, but when someone uses the command we want the bot to send an error message, for so reason it doesn't want to work

@Bot.command()
@commands.has_any_role(*roles)   
async def purge(ctx, limit = 10): 
        await ctx.channel.purge(limit=limit)
        embed = discord.Embed(description= "Cleared channel!")
        await ctx.send(embed=embed, delete_after=15)
@purge.error
async def purge_error(ctx, error):
    if isinstance(error, commands.MissingRoles):
        embed = discord.Embed(description= "You don't have the permissions to do that!")
        await ctx.send(embed=embed, delete_after=15)
        ctx.message.delete()```
unkempt canyonBOT
#

Hey @safe depot!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

โ€ข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

โ€ข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

sullen shoal
#
    raise MissingAnyRole(items)
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: 'Gold command'
#

also message.delete needs to awaited

outer violet
elfin pewter
slate swan
#
    await community.send(embed=embedCommunity,delete_after=5)
    await channelSuggest.send(embed=embedSuggest,delete_after=5)
    time.sleep(10)```
#

How come the time.sleep messes with my delete_after?

#

I wanna send a message, then once that message is deleted resend it. Basically keeping a pinned embed at the bottom of the channel.

#

I've tried asyncio.sleep but that made it spam lol

sullen shoal
#

this is an asynchronous library, you use asyncio.sleep to not block your script

slate swan
#

If you do asyncio.sleep(10)..

#

It sort of spams

#
  while True:
    await community.send(embed=embedCommunity,delete_after=5)
    await channelSuggest.send(embed=embedSuggest,delete_after=5)
    time.sleep(10)```
#

So uh any other ways xd

sullen shoal
#

send the entire code of the command

slate swan
#
@client.event
async def on_ready():
  client.ready = True
  await syst.log(xxx)
  community = client.get_channel(xxx)
  channelSuggest = client.get_channel(xxx)
  embedCommunity = discord.Embed(description="Community")
  embedSuggest = discord.Embed(description="Suggest")
  while True:
    await community.send(embed=embedCommunity,delete_after=5)
    await channelSuggest.send(embed=embedSuggest,delete_after=5)
    time.sleep(10)```\
sullen shoal
#

also please follow the PEP 8 style guide

slate swan
#

The xxx is just hidden info.

#

Don't want it in this channel so ignore it.

sullen shoal
#

youre not supposed to do anything on on_ready

slate swan
#

Why

#

It seems more efficient to making a message be sent then deleted..

elfin pewter
sullen shoal
#

on_ready is called multiple times

full valley
# sullen shoal yes

its doing the command, but its doing the whole command and not stopping at if statements even when theyre false.

full valley
# sullen shoal show code
#!q command -> Puts players into queue
@bot.command(name="queue", aliases=["q"], description="Join the queue")
@commands.check(is_issuer_in_game)
async def queue(ctx):
    if ctx.channel.id in allowed_channels:
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        game_id = ggid["game_id"]
        qsize = ggid["qsize"]
        pid = ctx.author.id
        pmention = ctx.author.mention

        if pmention not in playerqueue and len(lobby) < qsize:
            playerqueue.append(pmention)
            lobby.append(pid)
            info = pstats.find_one({"id": pid})
            if info is None:
                newuser = {"id": pid, "Wins": 0, "Losses": 0, "MMR": 1600, "Rank": "C"}
                pstats.insert_one(newuser)
            embed = discord.Embed(
                title=f"**{len(playerqueue)} of {qsize} players are in the queue**",
                description=str(ctx.author.mention) + " has joined!", color=0xE74C3C)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)

        if len(lobby) == qsize:
            games[game_id] = lobby.copy()
            lobby.clear()
            playerqueue.clear()
            game_id += 1
            settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
            embed = discord.Embed(
                title=f"**The queue reached {qsize} players**",
                description="Voting is now underway!",
                color=0xE74C3C)
            embed.add_field(name="Vote for random teams", value="!r", inline=True)
            embed.add_field(name="Vote for balanced teams", value="!b", inline=True)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(
                embed=embed,
                components=[
                    Button(style=ButtonStyle.red, label="Captains"),
                    Button(style=ButtonStyle.blue, label="Balanced"),
                    Button(style=ButtonStyle.green, label="Random")])
            res = await bot.wait_for("button_click")
            if res.component.label == "Captains":
                await ctx.invoke(bot.get_command('r'))
            if res.component.label == "Balanced":
                await ctx.invoke(bot.get_command('r'))
            if res.component.label == "Random":
                await ctx.invoke(bot.get_command('r'))

#!r command -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def r(ctx):
    if ctx.channel.id in allowed_channels: #and ctx.author.id in games.values():
        ggid = settings.find_one({"guild_id": ctx.guild.id})
        qsize = ggid["qsize"]
        game_id = ggid["game_id"]
        set_aid.add(ctx.author.id)
        if len(set_aid) == qsize/2:
            embed = discord.Embed(description="Random teams have been chosen",
                                  color=0xE74C3C)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix",
                             icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)
elfin pewter
full valley
#

when I click on one of the buttons, that invokes it, it sends the r command embed

#

when it shouldnt

#

oh hold on

#

I may be stupid

sullen shoal
wicked atlas
sullen shoal
#

i see

wicked atlas
#

Still confused as to what you're asking @elfin pewter

slate swan
#
    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1```
sullen shoal
#

seems like they want to know which one to install to get their bot working there

slate swan
#

So how does this get executed?

#

Via command?

sullen shoal
#

which should be asked in their support server

sullen shoal
#
from discord.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()
#

it will wait untill the bot is ready then execute the printer loop

#

self.printer.start() this starts it

slate swan
#

Can I put it into any cogs are got to explicitly use this one?

sullen shoal
#

you can put it in any cog

safe depot
slate swan
#

ah

#

Does it void the delete_after when the loop is reset?

#

Or can they overlap?

sullen shoal
#

dont know, never tried, you should try it yourself

slate swan
#

trying it rn ๐Ÿ™‚

elfin pewter
wicked atlas
slate swan
#
import os
import discord
import time
import datetime
import asyncio
from discord.ext.commands import cooldown, BucketType
from discord.ext import tasks, commands

import syst

class EmbeddedCog(commands.Cog):

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

    @tasks.loop(seconds=10)
    async def test(self):
      channelSuggest = self.guild.get_channel(xxx)
      channelHelp = self.guild.get_channel(xxx)
      embedSuggest = discord.Embed(description="xxx")
      embedHelp = discord.Embed(description="xxx")
      await channelSuggest.send(embed=embedSuggest,delete_after=10)
      await channelHelp.send(embed=embedHelp,delete_after=10)
      asyncio.sleep(12)```
#

Doesn't make errors and doesn't execute on_ready.

sullen shoal
#

where is self.guild

slate swan
#

Wdum?

#

It's getting the guilds channel.

sullen shoal
#

which guild

#

where is it defined

slate swan
#

Okay fair point..

#

Since it isn't being executed via cmd..

#

I have to define guild?

#

I don't remember how, so like guild = self.get_guild(id) ?

#

Or way off xd

sullen shoal
#

self is the instance of the class, the attribute bot is discord.ext.commands.Bot instance of your bot

slate swan
#

But don't remember how to define guild

#

I figured you didn't need to define guild.

#

Since it gets the channel?

sullen shoal
#

to get the guild object by ID, you can use Bot.get_guild

slate swan
#

bot won't work in cogs

#

self.get_guild ?

slate swan
#

says bot isn't defined everytime

sullen shoal
#

okay i see, your problem is something else

slate swan
#

how can I check if a member has a ping roles perm?

#

Yeah it isn't defining guild.

sullen shoal
slate swan
#

You don't have to define it defining channels.

#

I know how to use classes why did you send that

sullen shoal
#

well i wont waste more of my time. good luck

slate swan
#

hi

#

so i am trying to make a bot

#

and one of the commands i have set up is basically uhh

#

i have a txt file with phrases on different lines

#

and i want to print out a specific phrase, but i also want to print/get the line it's on

#

does that make sense?

sullen shoal
#

btw you may type two lines by the shortcut, shift+enter

#

i think str.find()

#

will work for you

slate swan
#

thanks!

slate swan
sullen shoal
#

you may give me an example of your input and output

sullen shoal
# slate swan does that make sense?

maybe you want something like,

mytxt = '''hello
world
xxx
707'''
phrase = input("enter the phrase: ")
phrases = mytxt.splitlines()
for index, p in enumerate(phrases):
    if phrase.lower() in p.lower():
        print(f"found phrase: {p}\nline: {index+1}")

?

slate swan
rustic temple
#

hello good friends

sullen shoal
#

you may use the open builtin function to read it

rustic temple
#

can someone give me a link to the tutorial for discord. py

#

that is commonly linked

sullen shoal
#

however its not async so it will block the code

slate swan
sullen shoal
rustic temple
#

thanks

west shuttle
#
    self.cogs = [
            {'name': 'Minecraft', 'obj': minecraft.Minecraft, 'active': True},
        ] 
        self.init_cogs()

    def init_cogs(self):
        for cog in self.cogs:
            self.bot.add_cog(cog['obj'](self.bot))

It doesnt upload the cog

sullen shoal
#

where is it

#

also why are you loading them like that?

#

any specific reason?