#discord-bots

1 messages Β· Page 598 of 1

boreal ravine
#

it wouldnt affect the list at all

slate swan
#

oh shit i did int(i)

#

not
i = int(i)

gaunt ice
#

@slate swan can we use embeds in loop

boreal ravine
slate swan
#

then make your bot check the data and unmute the muted users accordingly

gaunt ice
slate swan
#

😳

rare saddle
gaunt ice
#

@slate swan im making automeme cmd so i get the link randomly and it needs to be set as image in an embed , how to do it

#

just use the image url?

slate swan
#

embed.set_image(url=)

gaunt ice
#

okk

pallid harbor
#

homotrollius, there is no discord.Guild.member but it seems like discord.Member.guild is what I need.

slate swan
#

member.guild is the guild that the member is in

slate swan
#

as I've said before you can use guild.get_member(id), which returns not a nickname but a member object

boreal ravine
#

what did you think discord.Guild.member would show

#

🀨

pallid harbor
slate swan
#

Not rocket science

slate swan
patent surge
#
async def change_pfp():
  print("Pfp changed")
  with open("pick.png", "rb")as image:
    print(type(image.read()))
    await client.user.edit(avatar=image.read())```
Why I get Unsupported image type Error ?
slate swan
#

code

pallid harbor
slate swan
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

Downloading/streaming music from YouTube breaches their terms of service

brave flint
#

ok tq for remembering me

shy schooner
gaunt ice
#

yes

shy schooner
#

why is there nothing that happens to my friend's bot, like get a warn

slate swan
#

Because it's not popular

boreal ravine
slate swan
#

Not getting a warn doesn't mean it's allowed to

slate swan
boreal ravine
#

πŸ˜Άβ€πŸŒ«οΈ

slate swan
#

And I'm pretty sure lavalink does that

shy schooner
#

that means every bot in dsc that plays music is breaking yt's tos?

slate swan
#

No

#

1: They might play local music
2: They might play from a service that allows streaming/downloading
3: They are in contact with and YouTube allows them that (really doubt though)

shy schooner
#

are there any resources that my bot can use to play music without breaking laws

slate swan
#

Search on internet if there are music services that allows streaming (or downloading) music

arctic vapor
#

how do i check if a specific user has been pinged in an on_message?

#

ive tried

    @commands.Cog.listener()
    async def on_message(self,message):
        dontbepinged = self.bot.get_user(746384558831698012)
        #cluser = 746384558831698012
        if dontbepinged.id in message.content:
            print("pinged")
            await message.channel.send(f"pong")

and


    @commands.Cog.listener()
    async def on_message(self,message):
        dontbepinged = self.bot.get_user(746384558831698012)
        #cluser = 746384558831698012
        if dontbepinged.mentioned_in(message):
            await message.channel.send("pong")
slate swan
unkempt canyonBOT
arctic vapor
#

πŸ€” do i have to get_member instead of get_user?

sweet geyser
#

if message.content in "<@!<theird user id>>":

slate swan
sweet geyser
#

using this

slate swan
sweet geyser
#

wait wha?

slate swan
#

its like py if 'apple' in 'a':

sweet geyser
#

he wanted the bot to respond back if someone the specific user gets pinged right?

arctic vapor
#

ye it should be the other way round no?

slate swan
sweet geyser
#

i am terrible at english

slate swan
#

!d discord.ext.commands.Bot.user

unkempt canyonBOT
arctic vapor
#

bot.user would be the bot right? so if i want to see if im being pinged, i would do

dontbepinged = self.bot.get_user(746384558831698012)
if dontbepinged in message.mentions:
maiden fable
unkempt canyonBOT
slate swan
#

if that's your id

slate swan
slate swan
sweet geyser
#

or am i wrong?

arctic vapor
#

no

sweet geyser
slate swan
maiden fable
#

Is it tho?

tough verge
arctic vapor
#

just making it so that everytime im pinged it gets sent to another channel so its easier to find

sweet geyser
maiden fable
#

Then just do if len(role.mentions) ==0

arctic vapor
#

wouldnt that make it so all the pings are sent ?

tough verge
arctic vapor
#

just want it to be specific to me

#
@commands.Cog.listener()
    async def on_message(self,message):
        dontbepinged = self.bot.get_user(746384558831698012)
        
        if dontbepinged in message.mentions:
            print("pong")
            await message.channel.send("pong")
``` also this isnt working, am i supposed to get member instead of user?
slate swan
arctic vapor
#

yep

maiden fable
slate swan
arctic vapor
#

ive tried dontbepinged = message.guild.get_member(746384558831698012) too

slate swan
# arctic vapor yep

ok so dont mind the way i get the message object , but this seems to be completely applicable

#

is the cog loaded?

arctic vapor
#

yeah it is loaded

#

hmmm is there something really simple im missing

slate swan
#

try printing something when the on_message takes place to make sure that its really triggered or not

#

the self.bot.get_user part could be None . but i dont think so that its the problem since you might for sure be sharing a guild with your own bot

arctic vapor
#

yep the on_message is getting triggered

#

hmm

tough verge
arctic vapor
#

i dont think its self.message in the on_message πŸ€” everything else in the on message works except the ping

slate swan
#

and does get_user(746384558831698012) actually return a value or None

arctic vapor
#

intents are intents = discord.Intents.all()

slate swan
#

implied inside commands.Bot too?

arctic vapor
#

yep

arctic vapor
#

it returns None

slate swan
#

yea so the user is None somehow

#

does it share a guild with u

arctic vapor
#

yes πŸ€”

slate swan
#

hm , well you can use py if '@arctic vapor' in message.content:

#

the point that bot's returning None even with member intents is weird tho

arctic vapor
#

ahh sweet got it

arctic vapor
slate swan
#

It returns None because the member is not in cache

#

So you got to use something like

x = get_member(id) or await fetch_member(id)

So that it tries to get the member from cache (get_) and if it returned None it makes an API call (fetch_)

slate swan
#

Caching has nothing to do with mutual guilds...

#

member intents are enabled too

#

then it does

slate swan
#

late answer? yes

slate swan
#

Yeah no shit Sherlock

#

But it's not because the user shares a guild that it's obviously in the cache, that's my point

slate swan
slate swan
#

!d

unkempt canyonBOT
fallen anchor
#

Anyone know how to get the string after a option on slash commands? So like
/userinfo name: Hatsune Miku and when you print that the output is
Hatsune Miku

slate swan
#

depends on the library u r using

fallen anchor
edgy lion
#
class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = None
        self.bot.loop.create_task(self.connect_database())

    async def connect_database(self):
        self.db = await aiosqlite.connect("main.sqlite")

    @commands.command()
    @commands.cooldown(1, 3, commands.BucketType.guild)
    @commands.has_permissions(administrator=True)
    async def kick(self, ctx, member: discord.Member, *, reason=None):
        async with self.db.execute(
                "SELECT count from 'totalcases' where guild_id = ?",
                ctx.guild.id,
        ) as cursor:
            config = await cursor.fetchone()```

```py
Command raised an exception: ValueError: parameters are of unsupported type``` whats wrong?
slate swan
slate swan
fallen anchor
slate swan
fallen anchor
#

Example perhaps?

#

Just throwing things at me won't work.

full valley
#

Anyone able to help me out

fallen anchor
distant tree
#
Ignoring exception in view <SpotifyView timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='More Info!' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\cwals\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 365, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\cwals\Documents\GitHub\proxy-testing\cogs\views\views.py", line 40, in SpotifyButton
    if self.member.activities[1]:
IndexError: tuple index out of range
        if self.member.activities[1]:
            embed = discord.Embed(
                colour = self.member.activities[1].colour,
                title = 'Activity Information',
                description = "This task was completed without any errors."
            )
fallen anchor
full valley
# fallen anchor Depends

I’m trying to make a system, where I can store a gameid and 3 players for 2 teams.

I first thought about making 2 dictionaries, both with the same gameid as a key, and the players as the values.

Would there be a more efficient way to do this?

fallen anchor
distant tree
fallen anchor
slate swan
#

How do I make the bot delete every message that gets sent to the specific channel but it still gives the role to the user when they do the command correctly? It’s for my verify command


@client.event
async def on_message(message):
   if message.channel.id == 909671265864933406 and message.content.lower() == '*verify':
        fullaccessrole = get(message.guild.roles, id=909670961115201537)
        await message.author.add_roles(fullaccessrole)```
slate swan
fallen anchor
slate swan
rare saddle
#

Tell me how to make sure that the penultimate line every 60 seconds finds information about the remaining time of the participant's mute, and the last line takes 60 seconds every 60 seconds, and when the penultimate line displays information that there are 0 seconds left, the cycle stops and the mute is removed from the person

slate swan
#

and you would be having options from the decoratorpy @slash(options = [])

fallen anchor
fallen anchor
full valley
clear rapids
fallen anchor
clear rapids
fallen anchor
#

Afk for a sec

fallen anchor
# full valley tyvm
@client.command()
async def joinq(ctx):
  listname.append(ctx.message.author.id)
  if listname.len() == 6:
    await ctx.send('Added you to queue, 6/6')
    #additionalstuff
  if listname.len() > 6:
    await ctx.send(f'Add you to queue, {listname.len()}/6')
``` This should work
#

Really simple queue though

full valley
#

I’m sorry I don’t think I explained myself correctly

#

I’m wanting to store the player’s in the queue and working out what teams they are on, and link them with a game id

fallen anchor
rare saddle
#

How to make a loop so that every 60 seconds these two lines work

full valley
#

for each team

#

for context btw, this is my q command:

@bot.command(pass_context=True, name="queue", aliases=["q"], description="Join the queue")
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"]
        pid = ctx.author.id
        pmention = ctx.author.mention
        if pmention in playerqueue:
            embed = discord.Embed(
                title=f"{ctx.author.name}, you are already in the queue",
                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 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)
fallen anchor
#

I cannot help as much as far to store the gameid right now

#

But, you can do something like find a random game id and check if it isn't occupied and then create a new list with the teams in them

#
@client.command()
async def joinq(ctx):
  x = random.randint(1, 2)
  if listname2.len() > 6 and x == 2:
    listname2.append(ctx.message.author.id)
    #additionalstuff
  if listname1.len() > 6 and x == 1:
    listname1.append(ctx.message.author.id)
)```
#

Most basic way I can think of right now ^^

#

Don't have time to make a full out queue list right now, so I made the basic one I can think of

full valley
#

all g yeah, thanks for your help

rare saddle
#

How to make a loop so that every 60 seconds this line:

self.mutes.update_one({'member_id': member.id}, {'$inc': {'time_unmute': -60}})

Removed 60 seconds from mute time
And this:

unmute_time = self.mutes.find_one({'member_id': member.id})['time_unmute']

Checked how much time was left

Help me please

sick birch
rare saddle
sick birch
#

it allows you to run a loop every x seconds, and you can also find out how much time is left until the next iteration

fallen anchor
#

I've done set out an example of what I want to do

#

Any errors?

maiden fable
#

Mhm

forest blade
#

Information is in the pins

maiden fable
#

!pypi disnake

unkempt canyonBOT
slate swan
fallen anchor
#

Is it just not showing up in the commands list?

slate swan
#

no

#

oh

#

wait

#

no

#

@fallen anchor^

fallen anchor
#

So it's just not showing up in the slash list at all?

maiden fable
#

Caching Issues

#

Discord Issue. Wait for about 2 hours

slate swan
fallen anchor
# slate swan nope

Make sure you enabled intents for your bot and set them to all in the code, and then make sure you invited the bot with more than the bot, let me check and see what else needs to be enabled

maiden fable
#

Yea also make sure u have application.commands scope

maiden fable
fallen anchor
slate swan
maiden fable
#

Yups. But idk if that's test_guilds or guild_ids since the kwarg differs from lib to lib 😐

maiden fable
fallen anchor
slate swan
#

okok

#

thankss

fallen anchor
maiden fable
#

Which lib?

fallen anchor
#

discord-py-slash-command

slate swan
#

thinking of pulling xbox and Spotify connections, this embed is pretty as it is, any suggestions? wether i make a separate cmd, a second embed, idk what to do

maiden fable
#

Sorry never used that. Mind sending the docs link here?

fallen anchor
slate swan
maiden fable
fallen anchor
#

Alright

maiden fable
maiden fable
#

Wait u wanna get the Spotify and Xbox connections, right?

slate swan
#

mhm

maiden fable
#

!d discord.User

unkempt canyonBOT
#

class discord.User```
Represents a Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
slate swan
#

yeah ik how to get it

maiden fable
#

Ignore this

slate swan
#

thats easy, but what im trying to figure out is wether i should put connections in the same output message, but a separate embed

#

or just a separate command all together

maiden fable
#

Ah

#

Should be the in the same

slate swan
#

same message separate embed

#

yay more writing :D

#

this command took 2 minutes to learn what to do, and an hour 34 mins to write it

#

😭

maiden fable
#

Good embed tho

#

I would prefer making a paginator for that tho

slate swan
#

pages eeee

maiden fable
#

It is easy to make

slate swan
#

i can see how id do it

#

but ive never rly learned

#

would love to tho, dk where to start

maiden fable
#

Well I can help u to make a paginator with buttons if u want

slate swan
#

so testing a cmd wont be too easy

fallen anchor
maiden fable
slate swan
maiden fable
#

Sure

slate swan
#

i doubt that the way i went about it was smart

maiden fable
slate swan
#

if user has this perm:
emote is this
if user does not have this perm:
emote is that

maiden fable
#

BTW an easy way to make that embed would be

slate swan
#

did that for all perms 😬

maiden fable
#
perms = ctx.author.guild_permissions.items()
for perm, value in perms:
    embed.add_field(name=perm, value="true emoji" if value is True else "false emoji"
await ctx.send(embed=embed)
#

That will iterate through each permission and add an embed field

slate swan
#

did i really type 8.4kb of a command-

maiden fable
#

I don't care about kb but the lines and that work lemon_grimace

slate swan
maiden fable
#

Lmao

slate swan
maiden fable
slate swan
#

like administrator : true, send message : false...

maiden fable
#

No

slate swan
#

and so on

#

oh

maiden fable
#

It will see if the value is True or False

#

The value of the field will be true emoji if True else false emoji

slate swan
#

eek yk what i did for the embed

#
embed = discord.Embed(description=f"
General Server Permissions\nView Channels: {viewchan}\nManage Roles: {marl}...")```
#

basically, typing on phone is so hard especially when writing py

maiden fable
#

True

maiden fable
#

!d str.title

unkempt canyonBOT
#

str.title()```
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

```py
>>> 'Hello world'.title()
'Hello World'
```  The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

```py
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
```...
slate swan
#

eek

fallen anchor
maiden fable
#

Cool!

elder spoke
#

Hi can anyone explain me how can I make my bot detect if I tagged someone?

Example:

e$user[@example_User]

Bot returns:

example_User data

rare saddle
#

How to make the condition that if there is nothing in the collection, then stop the loop

maiden fable
unkempt canyonBOT
maiden fable
unkempt canyonBOT
#
len

len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
rare saddle
maiden fable
#

Wait u wanna check if mutes are 0?

rare saddle
maiden fable
#

Just use a try except, ig? I never used that module so cannot help you with this one, sorry

sick birch
#

But not sure about @tasks.loop

#

It most likely has a stop method as well

slate swan
#

yo anyone know the code make a discord bot dm people with a specific role

#

trying to ping people for a event

#

ive been trying for the past week and got nothing

#

plz help

valid perch
#

Loop over your guilds members, check if the role is in the members role. If so, dm them 🀷

slate swan
#

ok ill try that

#

How to i use process_commands

#

Send code

#

it worked like 2 weeks ago

#

It's because there is no member

#
@tasks.loop(seconds = 30)
async def staffrolesloop():
    mainguild = client.get_guild(884780660856881152)
    staffguild = client.get_guild(900459740063207464)
    staffrolesinmain = [884780660869447768, 884780660869447767, 884780660869447766, 884780660869447763, 884780660869447762, 884780660869447761, 884780660869447760, 884780660856881161, 884780660856881160]
    staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467437273772134)
    for g in mainguild.members:
        memberid = g.id
        for i in staffrolesinmain:
            role = discord.utils.get(mainguild.roles, id = i)
            if role in g.roles:
                member = staffguild.get_member(g.id)
                await member.add_roles(staffroleinstaffserver)
            else:
                None

@tasks.loop(seconds = 30)
async def staffhqstaffrolesloop():
    mainguild = client.get_guild(884780660856881152)
    staffguild = client.get_guild(900459740063207464)
    hqrolesinmain = [884780660869447763, 884780660869447762, 884780660869447761]
    staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900501559027331082)
    for g in mainguild.members:
        for i in hqrolesinmain:
            role = discord.utils.get(mainguild.roles, id = i)
            if role in g.roles:
                member = staffguild.get_member(g.id)
                await member.add_roles(staffroleinstaffserver)
                time.sleep(1)
            else:
                None
            


@tasks.loop(seconds = 30) 
async def hqstaffrolesloop():
    mainguild = client.get_guild(884780660856881152)
    staffguild = client.get_guild(900459740063207464)
    staffhqrolesmain = [884780660869447767, 884780660869447766, 884780660869447763]
    staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467350179033120)
    for g in mainguild.members:
        for i in staffhqrolesmain:
            role = discord.utils.get(mainguild.roles, id = i)
            if role in g.roles:
                member = staffguild.get_member(g.id)
                await member.add_roles(staffroleinstaffserver)
                time.sleep(1)
            else:
                None


@tasks.loop(seconds = 30)
async def managementrolesloop():
    mainguild = client.get_guild(884780660856881152)
    staffguild = client.get_guild(900459740063207464)
    managementrolesmain = [884780660869447768, 884780660869447767, 884780660869447766]
    staffroleinstaffserver = discord.utils.get(staffguild.roles, id = 900467392122069043)
    for g in mainguild.members:
        for i in managementrolesmain:
            role = discord.utils.get(mainguild.roles, id = i)
            if role in g.roles:
                member = staffguild.get_member(g.id)
                await member.add_roles(staffroleinstaffserver)
                time.sleep(1)
            else:
                None


#

there is tho, theres 100 members in the discord

slate swan
slate swan
slate swan
#

it's because member is None

#

"NoneType"

#

there is members tho

#

@slate swan what could it be

slate swan
# slate swan

It says right here that member is none so no member is being defined.....

#

there is members in both servers

#

could it be todo with intents

#

Try using jishaku

#

what is it

#

!pypi jishaku

unkempt canyonBOT
slate swan
#

done now what

#

<prefix>jsk <command>

slate swan
rare saddle
#

How to correctly check if the collection contains at least one element

patent lark
slate swan
#
from discord.ext import commands

bot = commands.Bot(commands_prefix='o!')

@bot.commands()
async def yur(ctx):
    await ctx.reply('yesirrrr')

    bot.run ```
#

why it aint working?

#

Remove the s in bot.commands

#

@slate swan

slate swan
#

And

#

Fix your indentation

#

?

#

Bot.run

final iron
slate swan
#

yh i got the token in i just removed for safety

#

still dont workπŸ€”

slim whale
#

is it possible to make a command add command?

rare saddle
#

How to check if a collection is empty or not? (mongodb)

forest spear
#

How can I display the data written in my json file?

#

I tried doing a for loop but it didn't seem to work for it

manic wing
slate swan
#

yea it did not work

#

still cant dm people

forest spear
manic wing
manic wing
manic wing
manic wing
#

for k in data: print(k)

slate swan
#

oh

forest spear
#

I have

for data in data['users']:
         yes = data['id']

Etc like that but it's not working

#

Looks unidented because I wrote it

manic wing
#

in a loop, you cant give the name to the data

#

so try py for k in data['users']: yes = k['id']

#

you can also print(data)

slate swan
forest spear
#

Ok one sec

manic wing
forest spear
manic wing
#

can you show the code?

forest spear
#
@client.command()
async def showquote(ctx):
    with open('quote.json', 'r') as f:
        data = json.loads(f) 
    for f in data['users']:
        yes = f['id']
        yes3 = f['username']
        yes1 = f['time']
        yes2 = f['quote']
        
    embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
    await ctx.send(embed=embed)β€Š
manic wing
#

you did json.loads(f)

#

its json.load(f)

forest spear
#

Gives keyerror 'id'

slate swan
manic wing
#

so you might consider print(f) to see what keys there might be.

#

maybe you do not need the for loop?

forest spear
manic wing
#

you're welcome.

tulip oracle
rare saddle
tulip oracle
#

well if it couldnt find_one why would you need to check that the collection has one element

tulip oracle
forest spear
rare saddle
tulip oracle
#

the what

rare saddle
tulip oracle
#

i dont know what you are trying to do but if the code you are looping through above the screenshot is a collection that is a list

rare saddle
# tulip oracle the what

I do the command mute and when I issue one line, which takes away -1 every second and thus, when the time is over, mute is removed

tulip oracle
#

to do a timed unmute?

#

why not just compare the nowtime with a settime in ur db

rare saddle
tulip oracle
#

erm interesting lmao..

tell me what self.mutes is raw

rare saddle
#

I did it using time, or rather a timestamp

#

self.mutes it's collection

tulip oracle
#

yes is self.mutes = mycluster["something"]["something"]

tulip oracle
#

are you sure you wrote this code

rare saddle
#

I'm a beginner, so I write this way

tulip oracle
#

this is not beginner code

#

which im asking because you are asking a beginner question

#

but netherless.

rare saddle
#

I'm slightly better than a beginner

#

So you know what to do?

tulip oracle
#

....

#

well yes but you will need to add another check

tulip oracle
#

if self.mutes = col["something"]["something"]
then just use
collection = list(col.find())
and check that the list is not None

#

i still dont understand your code and you wont tell me what i want to know so thats the best i can do

tulip oracle
#

like i said. i still dont know cuz you wont tell me what self.mutes is raw

rare saddle
tulip oracle
#

and ive told you 2 different ways. how can you write all this mongo code and not know how to check if the collection has an element in it

rare saddle
slate swan
tulip oracle
tulip oracle
#

this isnt your code lmao

rare saddle
#

Otherwise, how did I create a database and collections according to yours?

dusk dust
#
questions = [
    'Question1',
    'Quesiton2',
    'Question3',
    'Question4',
    'Question5',
    'Question6',
    'Question7',
    'Question8',
    'Question9',
    'Question10'
]

@bot.command(name='apply')
async def name_here(ctx):

    await ctx.reply('attention', mention_author=False)
    await ctx.author.send('text here')
    await asyncio.sleep(10)

    # Gen 'questions' randomly without repeating 

i wanted the bot to generate these strings (questions) randomly, but without repeating. Example: [1,1,2,3,4,4] any1 can help me?

tulip oracle
#

?

#

just use random.choice() on your list

fathom ember
#

code: py time2 = t.total_seconds / 60
error: unsupported operand type(s) for /: 'builtin_function_or_method' and 'int'
please help

tulip oracle
#

check what t.total_seconds is

fathom ember
# tulip oracle check what t.total_seconds is

counting time

t = timedelta(days = 30 - datetime_object.day, hours = 0 - datetime_object.hour, seconds = 0 - datetime_object.second , microseconds = 0 - datetime_object.microsecond )
tulip oracle
#

no what does it return

#

but by the way u used microsecond attr i imagine its a float. in that case you should of learnt basic python as you would know to use // operator

fathom ember
#

error like this: <built-in method total_seconds of datetime.timedelta object at 0x7fa730239270>

tulip oracle
#

still not what i asked

slate swan
tulip oracle
fathom ember
# tulip oracle still not what i asked

you ask for this:

t = timedelta(days = 30 - datetime_object.day, hours = 0 - datetime_object.hour, seconds = 0 - datetime_object.second , microseconds = 0 - datetime_object.microsecond )
print (t.total_seconds)

respone: <built-in method total_seconds of datetime.timedelta object at 0x7f83a9b60150>

fathom ember
tulip oracle
#

just format it to a string

rare saddle
#

How to add mute role to all channels when the command is activated

tulip oracle
#

right now its just calling the function

tulip oracle
rare saddle
tulip oracle
#

just use discord.TextChannel.set_permissions(role,*permissions=[bool])

regal shell
#

Ik this isn’t code related but what do y’all use for hosting?

slate swan
#

i need suggestions for what to do on the second page. i wanted to do connections but discord doesnt provide that data to bots

tulip oracle
#

who cares its your bot do as you please

slate swan
tulip oracle
#

you can work with discord.Member.guild_permissions

tulip oracle
#

ok we dont give u ideas here we just help run ur code

slate swan
#

you were saying

tulip oracle
#

yes we help run ur discord-bot code

slate swan
#

i can make it bigger if needed

tulip oracle
#

you wanna wait for someone to give u ideas

#

sure be my guest

slate swan
slate swan
tulip oracle
slate swan
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
slate swan
tulip oracle
#

how ever you gain your role obj
if role_obj in member.roles:

dusk dust
tulip oracle
#

no? its going to pick one random element in that list

slate swan
#
targex = omega.get_channel(int(chanid))
await ctx.message.delete()
async for message in targex.message.channel.history(limit=None).filter(lambda m: m.author == omega.user).map(lambda m: m): ```

Targex comes from the function args. It returns "targex has no value 'message'"
visual island
#

targex is already a channel

slate swan
#

but targex.history doesn't work either

visual island
#

.flatten() it

#

!d discord.AsyncIterator.flatten

unkempt canyonBOT
#

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

Flattens the async iterator into a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") with all the elements.
visual island
#

oh wait, youre iterating it with async iter

slate swan
visual island
#

targex is None

#

Is it the correct channel?

slate swan
#

Wait it worked, I was using dm channel πŸ˜…

visual island
regal shell
#

Anyone know how I fix this?

visual island
#

the syntax is as the following: for <var> in <iterable>:

regal shell
#

Nvm I fount the mistake lol thanks

final iron
rare saddle
#

Please tell me what this means? I register the command and now

regal shell
final iron
#

I wouldn't use it if I were you

regal shell
#

I’m following his β€œmake a bot” rewrite trying to learn

regal shell
#

Aye I fixed it

full valley
#

Hi guys anyone know how to only β€˜activate’ a command when 3 people who use it say it?

rare saddle
#

Why doesn't the bot add role permissions to the channel and how to do it so that if the rights for the role are already set, then nothing needs to be done

slate swan
#

Hi, i want to make a command that shows the renaming cool-down of all other commands. what should i use? is there any default methods to check?

rare saddle
final iron
rare saddle
slate swan
slate swan
final iron
#

!d discord.Permissions.speak

unkempt canyonBOT
slate swan
slate swan
#

not sure why

slate swan
#

could I ask for help with a problem?

opaque plinth
slate swan
#

I want to have a while true loop which checks if a certain event happens and if that event happens, it should send a message to a specific discord channel. Now I coded some bots already and I know how the basics work, but how could I "build" this? I couldn't do it in a task because it is supposed to stay in the while true loop permanently

#
    while True:
        response = recv(sock, 1024)
        pprint(response)
        if (response == "PING :tmi.twitch.tv\r\n"):
            send(sock, f"PONG :tmi.twitch.tv\r\n")
            continue
        if (substring in response):
            sendmessage(response)
            
def sendmessage(response):
    await channel.send("Text")

It should work like this

#

ah I think I know how I could do it, I could ask a command to trigger that while loop, I wont be able to start a new command but that wont matter

slate swan
#

How to change bot status (not activity) using python

#

Anybody know a good buttons tutorial for disnake i have no idea where to start and docs werent to helpful

slate swan
slate swan
patent lark
unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

β€’ [`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")

β€’ [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
patent lark
#

!d discord.ActivityType

unkempt canyonBOT
#

class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity"). This is used to check how to interpret the activity itself.
slate swan
#

custom status

patent lark
#

thats exactly what i pointed you to ^

slate swan
#

Its like watching, plqying

slate swan
patent lark
slate swan
patent lark
patent lark
slate swan
#

Right there

#

ok nvm drop the topic

#

can we change about me?

slate swan
patent lark
#

in your developer portal, the description is the about me

slate swan
#

Yeah

#

directly from python?? Like changing every 24 hrs

slate swan
slate swan
slate swan
pliant gulch
#

Bots don't have access to this custom status

slate swan
#

Your bots about me needs to be changed in the the dev portal

slate swan
slate swan
#

Nah Nah I was just thinking

#

Alr

terse flare
#

how to fix this bug in typing.py? I'm newbie and trying to make my first bot but module errors is...

ornate glade
#

So do y'all know how one of the features you can do with Discord is copy the link of images and then when you copy the link it gives you https://cdn.discordapp.com/yadayda Is there a way to do that but with Discord py? I'm trying to take the user input of an image essentially.

I tried to search up the way to do it, but I haven't gotten any luck.

Here's my code for trying to get a user's image:

4th field

def check4(msg4):
return msg4.author.id == member.id and msg4.channel == channel

await channel.send("Any screenshots? If you do, paste in a link to the screenshot (i.e. imgur.) If you don't type None")

try:
msg4 = await client.wait_for('message', check=check4, timeout=120)

except asyncio.TimeoutError:
await channel.send("You didn't reply in time.")
guild = member.guild
await channel.set_permissions(member, send_messages = False)

role = discord.utils.get(guild.roles, name='InReports')
await member.remove_roles(role)
agile shadow
#

my new lines aren't working and I can't seem to understand why

worthy wagon
#

How do you get an authors permissions?

#

I know ctx.author.roles exists

#

I'm not sure ctx.author.permissions exists Lol

#

w

patent lark
#

hm

agile shadow
# patent lark send your code.

I pull a string from an API and then I just send it in an embed description, other things like backtick text or bold text render but not \n

#

no need to show code

patent lark
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
worthy wagon
#

checked that already

patent lark
#

let me check the docs @worthy wagon

#

ah

worthy wagon
#

appreciate it

patent lark
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
agile shadow
#

snow do you have any idea why?

patent lark
#

im really not sure, as far as im aware if your \n is inside the string it should add a new-line.

agile shadow
#

I thought so too

patent lark
#

@agile shadow you can use guild_permissions

patent lark
#

oh

#

i pinged the wrong person

#

sorry ghoul

patent lark
#

iterate through ctx.author.guild_permissions using a for loop.

worthy wagon
#

that's what I wanted to do.

#

Thank you so much man!

patent lark
#

yep!

agile shadow
#

this may be quite far fetched, or is it because im doing news = news.replace('"', "")

#

that shouldn't affect anything though because its already in a string

slate swan
#

does anyone know a decent api or how i could fetch tiktok profile data? including followers, following, likes etc

agile shadow
slate swan
#

thanks

agile shadow
devout iris
slate swan
#

Cant really see it tho

devout iris
#

i can see

#

But i have only 100 line

pliant gulch
#

Whatever tk is, it isn't a string

#

Its a dict from what the errors says

devout iris
#

it says 723 lines

devout iris
pliant gulch
#

Those are the lines from the library

devout iris
#

Then how can i do it str?

agile shadow
#
f"**{Emoji.CHECKMARK} Here are all my modules!**\n\n__**{Emoji.NOTIFICATION} {bot.user.name} News**__\n{await get_latest_news(latest_news_id)}"``` @patent lark do you see anything wrong in this?
devout iris
#

Datas from json lines

#

So they are dict

agile shadow
#

json["token"]

slate swan
#

Nvm you want to do 2 new lines prob

agile shadow
#

yes lol

#

hold on lemme get an image of what it looks like

#

so confusing

slate swan
agile shadow
#

so the \n should be intepreted

slate swan
#

Yeah ik lol

agile shadow
#

what I don't understand, is why the \n isn't doing anything

slate swan
#

Nvm i know what you mean now

ornate glade
agile shadow
ornate glade
#

Ah

slate swan
#

@agile shadow try making a list and use "\n" .join() i think its like that

agile shadow
#

what

slate swan
agile shadow
#

that's not needed

ornate glade
#

Spaces in embeds are weird. If you wanted a bigger space in an embed, you will have to use a blank character, which is chr(173). Idk if that helps, or is what you want. \n will not work the way it's supposed to on embeds.

ornate glade
#

that's the blank character

slate swan
ornate glade
#

so having a field of just chr(173) will make the space.

agile shadow
#

ah

#

I never knew that was a builtin function

#

you learn something new everyday

ornate glade
#

For example:

embed = testembed.add_field(name=chr(173), value=chr(173))

#

Hopefully that helps, the space may be too big though.

agile shadow
#

let me try

#

actually, @ornate glade I want to understand first why the first \n\n and second \n worked, but not the rest

#

Ah, I know why, it's because the \n isn't being intepreted, it's like I'm doing

""\n""```
slate swan
agile shadow
# slate swan Huh?

I don't know how to say it, but it's like I'm not using the string in a way where \n would be applied

ornate glade
#

Is the problem fixed though?

agile shadow
#

yes, but I'll have to do some refactoring to how I get that string in the first place, I was pulling it off an API but that might have to just be a local file or something I update periodically

agile shadow
#

yea

heavy folio
slate swan
heavy folio
#

and disnake is a fork of dpy wdym

slate swan
slate swan
agile shadow
#

@slate swan @ornate glade πŸ‘ thanks

slate swan
pliant gulch
#

In my wrapper, should I dispatch user: lefi.User to READY event callbacks or just make users access the client's user through lefi.Client.user

heavy folio
pliant gulch
#

Any specific reason?

#

I'm only dispatching it right now as I get it from the gateway after parsing everything

magic ore
#

there isn't really a reason to pass it considering they can just access it from their lefi.Client instance

#

in my opinion at least

pliant gulch
#

Wouldn't it be more verbose to make users use it through the first way as either way, lefi.Client.user would be None until READY is recv'd from the gateway

#

This is mostly a design choice though, I don't really care where it can be accessed or at what time

#

Current examples look like ```py
@client.on("ready")
async def on_ready(_: lefi.User) -> None:
print("logged in")

#

And it's sort of bothering me as lefi.Client.user is also there

devout iris
#

Hey, how can i add my pc stats to bot stats?

#

ram usage, processor usage, operating system infos and stats

cerulean osprey
#

Essentially I am working on an auto softban that bans members that type in a certain channel, and have less than 2 roles. The code I have is

if message.channel.id == 909685766244945921:
        print('Nerd')
        if len(message.author.roles) <= 2:
            print('Bozo')
            await client.send_message(message.author , 'You have been softbanned due to falling for an obvious trick... (nitro scam)')
            await message.author.ban(reason = 'You typed in the kick channel!')
            await message.guild.unban(discord.Object(message.author.id))

The print statements are for troubleshooting purposes, dont mind them. I am getting an error after I added the client.send_message line. the error is
AttributeError: 'Bot' object has no attribute 'send_message'

cerulean osprey
#

Yes

sullen shoal
#

event*

visual island
sullen shoal
#

so to send messages in a channel, first you have to get the channel object of it, message.channel

visual island
#

your code has been invalid since v1

cerulean osprey
#

Ah so these internet people suck Pain understandable, thank you

sullen shoal
#

were you expecting us to spoonfeed

pale zenith
cerulean osprey
#

Tbh thats the first time Ive ever been mislead, big scam. But Ill bookmark the docs, thank you

pale zenith
#

no prob :DDD

forest spear
#

Hello, I'm having a problem I'm not able to show the data stored in my json file

@client.command()
async def showquote(ctx):
    with open('quote.json', 'r') as f:
        data = json.loads(f) 
    for f in data['users']:
        yes = f['id']
        yes3 = f['username']
        yes1 = f['time']
        yes2 = f['quote']
        
    embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
    await ctx.send(embed=embed)β€Š
``` that's the code but it gives keyerrors and when I just try "print(f)" it shows the data in there can someone help
hushed siren
#

its giving me this error when i use tempmute command
the error:

 raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "time".

and the code:

@client.command()
async def tempmute(ctx, member: discord.Member, time: int, d, *, reason=None):
    guild = ctx.guild

    for role in guild.roles:
        if role.name == "Muted":
            await member.add_roles(905765835791036477)

            embed = discord.Embed(title="Muted!", description=f"{member.mention} has been tempmuted ", colour=discord.Colour.light_gray())
            embed.add_field(name="reason:", value=reason, inline=False)
            embed.add_field(name="time left for the mute:", value=f"{time}{d}", inline=False)
            await ctx.send(embed=embed)

            if d == "s":
                await asyncio.sleep(time)

            if d == "m":
                await asyncio.sleep(time*60)

            if d == "h":
                await asyncio.sleep(time*60*60)

            if d == "d":
                await asyncio.sleep(time*60*60*24)

            await member.remove_roles(role)

            embed = discord.Embed(title="Unmute (temp) ", description=f"Unmuted -{member.mention} ", colour=discord.Colour.light_gray())
            await ctx.send(embed=embed)
            return
devout iris
forest spear
hushed siren
forest spear
#

Yes

hushed siren
#

okay ill try

forest spear
#

Also you wrote "if role.name =="Muted":" you don't need that part since you added the role ID you want to give

forest spear
heavy folio
#
Ignoring exception in view <UserInfoView timeout=15.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='View More Info' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\user\Desktop\theBot\cogs\misc.py", line 201, in receive
    await interaction.response.send_message(embed=success_embed, ephemeral=True)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 526, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 191, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.description: This field is required
```i have this error, i ran the command on someone who only has the @ everyone role
```py
        if len(self.member.roles) == 1:
          pass
        else:
          yourRoles = ', '.join([role.mention for role in reversed(self.member.roles[2:])])
          success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)
#

i even did ```py
# checks member's roles
if len(self.member.roles) == 1:
print("member doesnt have any other roles beside @everyone")
print(self.member.roles)
await interaction.response.send_message("done")
return
else:
yourRoles = ', '.join([role.mention for role in self.member.roles[2:]])
# success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)

      print("member has other roles other than @everyone")
      print(self.member.roles)
      await interaction.response.send_message("done")
      return

and what it printed was:py
member doesnt have any other roles beside @everyone # on someone who only has @everyone
[<Role id=879311327720538142 name='@everyone'>]
member has other roles other than @everyone # on myself
[<Role id=879311327720538142 name='@everyone'>, <Role id=879573209203236906 name='verified ── . ΰΉ‘*q'>, <Role id=883893045781729310 name='admon'>, <Role id=902489063368589323 name='bot mod'>, <Role id=896652444916924416 name='donkvolopers'>]

forest spear
#

Can you show your entire code

heavy folio
#

it worked perfectly fine previously with 1 field but without a desc

maiden fable
devout iris
forest spear
maiden fable
#

Well try printing the embed

heavy folio
#

wdym

maiden fable
#

print(embed)

devout iris
forest spear
#

Remove the error handler you have or make an else statement and type "print(error)" in the statement

heavy folio
maiden fable
#

Try doing print(str(embed))

compact gorge
#

hello, im new to discord bot(coded by python), is replit.com ok for coding bot?

heavy folio
compact gorge
maiden fable
heavy folio
#

print?

compact gorge
#

where should i start for coding

maiden fable
maiden fable
unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

maiden fable
#

Okay... Gimme 1, lemme tell you what to do

forest spear
#

Sorry code might be messy I'm on phone

maiden fable
compact gorge
#

i mean the coding part

forest spear
compact gorge
#

@maiden fable

compact gorge
forest spear
heavy folio
forest spear
compact gorge
forest spear
heavy folio
pliant gulch
# devout iris

You need to pass the embed object to the embed kwarg in send

#

send(embed=...)

compact gorge
devout iris
#

i did it now

#

But there is an error again

pliant gulch
#

bot is a commands.Bot instance

#

Its gonna send that out

devout iris
pliant gulch
#

Or you can do name for the bot's username

devout iris
#

bot.user is working

#

But now others isnt working

#

bot.is_owner

slate swan
devout iris
#

Also bot sends 2 messages at the same time

slate swan
forest spear
slate swan
forest spear
#

Can someone help me too I'm having a problem I'm not able to show the data stored in my json file

@client.command()
async def showquote(ctx):
    with open('quote.json', 'r') as f:
        data = json.loads(f) 
    for f in data['users']:
        yes = f['id']
        yes3 = f['username']
        yes1 = f['time']
        yes2 = f['quote']
        
    embed = discord.Embed(title="Saved Quotes", description=f"{yes}\n{yes3}\n{yes1}\n{yes2}")
    await ctx.send(embed=embed)β€Š```
 that's the code but it gives keyerrors and when I just try "print(f)" it shows the data in there can someone help
compact gorge
hushed siren
#

hey im trying to make an custom prefix command the bot runs and stuff but when i try the command its giving me a error

File "main.py", line 22, in get_prefix
    return prefix[str(message.guild.id)]
KeyError: '905126423902167041'

the line its giving me error in:

def get_prefix(client, message):
    with open("prefixes.json", "r") as f:
        prefix = json.load(f)
    return prefix[str(message.guild.id)]
slate swan
scenic lark
glass rock
#

can someone suggest some APIs to use with a bot with get request? Not looking for anything specific

hushed siren
scenic lark
#

the function you made is only supposed to return with the server ID

visual island
high pollen
#

Any good databases?

stoic bridge
warped basin
#

uhhh

#

can someone show me how to host my bot on vultr

#

pls man im suffering

slate swan
devout iris
#

How can i make changing status

high pollen
high pollen
maiden fable
high pollen
#

use this

#

replace idle with what ever u want

#

dnd or online or offline or idle

#

add it in on_ready function

high pollen
forest spear
devout iris
#

i mean, there is 3 status
They are changing in 10 secs

#

Like that

high pollen
devout iris
#

A sec

forest spear
slate swan
forest spear
#

Left*

warped basin
#

i used the site manager

#

in the top left

forest spear
#

And you put the IP and user as root or whatever vultr gave you and you put in the password it gave you?

high pollen
warped basin
#

yep

devout iris
warped basin
#

im not getting any errors it just wont let me connect to the server

devout iris
#

Status changing auto

forest spear
#

Have you used the console on the vultr website to update it?

#

Sudo apt-update

warped basin
#

lemme try

high pollen
devout iris
#

Still u r not understand me lol

devout iris
#

Nvm

slate swan
brittle ingot
#

its a status cycle.

warped basin
#

πŸ˜”

#

why does this only happen to me

brittle ingot
#

and if i remember correctly it is a task like Okimii is saying

slate swan
#

You have to wait for the bots cache to be ready to change its presence

forest spear
warped basin
high pollen
glass rock
#

how can I make bot messages an embed instead of text

forest spear
slate swan
slate swan
brittle ingot
#

filzilla site setup ^

high pollen
brittle ingot
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
glass rock
# slate swan Wdym?

i mean currently my bot returns text and it looks terrible. I have seen some bots return an embed or like a weird outline thing around the text. What is the command for that? If you see above the python bot didnt exactly return text

brittle ingot
slate swan
# high pollen wdym by task?
 ​async​ ​def​ ​startup_function​(): 
 ​    ​#Β WeΒ willΒ letΒ itΒ waitΒ untilΒ theΒ botΒ isΒ fullyΒ loaded. 
 ​    ​await​ ​bot​.​wait_until_ready​() 
 ​    ​#Β NowΒ let'sΒ setΒ theΒ bot'sΒ statusΒ toΒ onlineΒ andΒ theΒ gameΒ activityΒ toΒ '!help' 
 ​    ​await​ ​bot​.​change_presence​(​status​=​disnake​.​Status​.​online​, ​activity​=​disnake​.​Game​(​name​=​'!help'​)) 
  
 ​#Β Now,Β weΒ wantΒ toΒ knowΒ whenΒ ourΒ botΒ hasΒ startedΒ up.Β WeΒ willΒ useΒ theΒ 'on_ready'Β event. 
 ​@​bot​.​event 
 ​async​ ​def​ ​on_ready​(): 
 ​    ​print​(​"LoggedΒ inΒ as​\n​"​, ​bot​.​user​, ​"​\n​"​, ​bot​.​user​.​id​, ​"-------------"​) 
  ​#Β NowΒ let'sΒ makeΒ ourΒ startup_function()Β run! 
 ​bot​.​loop​.​create_task​(​startup_function​())

Example from: @dapper cobalt

slate swan
glass rock
#

yes exactly

slate swan
forest spear
glass rock
#

thanks

brittle ingot
#

If you are talking about getting your help command to print out an embed instead of a message you will need to subclass your help command

slate swan
# glass rock thanks

Basic code of a embed btw yes theirs way more fields in the class

await ctx.send(embed=embed)

Btw its just a example dont copy paste it if you dont understand it

glass rock
#

thats it?

#

wow

slate swan
glass rock
#

ty

slate swan
slate swan
forest spear
#

Sorry for the ping @brittle ingot
{'users': [{}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:22 PM UTC', 'quote': ['deez nuts']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:25 PM UTC', 'quote': ['deez']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:26 PM UTC', 'quote': ['deez nuts']}, {'id': 663415559630880778, 'name': 'CIA#2771', 'time': 'Mon, 15 November 2021, 09:27 PM UTC', 'quote': ['deez']}]}

That's the print

glass rock
brittle ingot
#

!paste

slate swan
glass rock
slate swan
glass rock
#

oof it refused to connect.

#

maybe its some firewall @slate swan is tere an alternative link

slate swan
glass rock
#

drat

slate swan
boreal ravine
unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
brittle ingot
#

@forest spear Your trying to fetch all information and put it into an embed? it looks like you are only defining the embed for one entry?

forest spear
boreal ravine
#

its how python works

forest spear
#

It just shows me more error lemme show you one sec

boreal ravine
#

you don't have to, if you wanna access the id key you gotta index users first like ["users"]["id"] since users is a list

forest spear
#

Yeah that's what I did it shows keyerror on users now

boreal ravine
#

hm weird

brittle ingot
#

this is what i came up with. Disclaimer its been months since i worked with Python and very rarely do i work with JSON in python. so hopefully someone can fix any mistakes:

@client.command()
async def showquote(ctx):
    embed = discord.Embed(
        title=" ",
        description= " ", 
        color=discord.Colour.red()
    )
    with open('quote.json', 'r') as f:
        data = json.loads(f) 
        users = data.users
        for user in users: 
        embed.add_field(
            name=f"{user.id} | {user.name}",
            value=user.quote.join(', '),
            inline=False
        )
        
    await ctx.send(embed=embed)
#

if you want to select a random one you should be able to run random.choice(users) assign that to a variable and use that variable to select the info from the randomly chosen quote.

sullen shoal
brittle ingot
#

^

forest spear
#

Lemme try it thanks for the help

#

Sorry but they both don't work give the error "the json object must be str, bytes or bytearry not TEXTIOWrapper"

sullen shoal
#
{
    "users":[
        {
            
        },
        {
            "id":663415559630880778,
            "name":"CIA#2771",
            "time":"Mon, 15 November 2021, 09:22 PM UTC",
            "quote":[
                "deez nuts"
            ]
        },
        {
            "id":663415559630880778,
            "name":"CIA#2771",
            "time":"Mon, 15 November 2021, 09:25 PM UTC",
            "quote":[
                "deez"
            ]
        },
        {
            "id":663415559630880778,
            "name":"CIA#2771",
            "time":"Mon, 15 November 2021, 09:26 PM UTC",
            "quote":[
                "deez nuts"
            ]
        },
        {
            "id":663415559630880778,
            "name":"CIA#2771",
            "time":"Mon, 15 November 2021, 09:27 PM UTC",
            "quote":[
                "deez"
            ]
        }
    ]
}```
#

hm

forest spear
#
with open('quote.json','r') as f:
                      data = json.load(f)
for f in data['users'][1]:
        yes = f['id]
        print(yes)```
#

Looks unidented but I wrote the code down so yeah

sullen shoal
#

you forgot a '

#

after id

forest spear
#

Sorry I wrote the code down on phone it's there on my PC tho

sullen shoal
#

send the entire traceback that code looks fine

#

oh i see

sick birch
forest spear
#
  File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(args, **kwargs)
  File "C:\Users\jackie\Desktop\yes_bot\bot.py", line 1766, in showquote
    data = json.loads(f)
  File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\json__init__.py", line 339, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

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

Traceback (most recent call last):
  File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(ctx.args, **ctx.kwargs)
  File "C:\Users\jackie\AppData\Local\Programs\Python\Python39\lib\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: the JSON object must be str, bytes or bytearray, not TextIOWrapper```
forest spear
#

I find databases like SQL or mongoDB hard unless theres like a tutorial for literally every possible thing you can do with them

sullen shoal
#

and you have sliced the list so the element f of the for loop are the key names as str

sick birch
#

well using json is a double edged sword

#

sure it's easy but more times than not i'll come back and bite you later on

sick birch
#

f is actually a string, each of the keys in the subdict you specify

#

so it panics when you ask for f['id']

full valley
#

How would I make an optional argument for a command?

E.g. the member uses !stats which gives them their stats, or they can do !stats @ user which gives the users stats?

sick birch
full valley
#

But doesnt that mean I have to make arg 1 = to something as default?

sick birch
#

You do

full valley
#

but arg 1 is ctx

sick birch
#

Oh wait

#

arg1 is the mandatory argument, so you should leave it

forest spear
sick birch
#

only optional arguments need a =

sick birch
full valley
#

I kind of want something like this

@bot.command()
async def stats(ctx, member: commands.MemberConverter):
sick birch
sick birch
boreal ravine
heavy folio
#
        success_embed = discord.Embed()

        # checks member's roles
        if len(self.member.roles) <= 1:
          pass
        else:
          yourRoles = ', '.join([role.mention for role in self.member.roles[1:]])
          success_embed.add_field(name=f"Roles [{len(self.member.roles) - 1}]", value=yourRoles, inline=False)
```so if i only have the everyone role - the bot will return this error: ```py
Ignoring exception in view <UserInfoView timeout=15.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='View More Info' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\user\Desktop\theBot\cogs\misc.py", line 201, in receive
    await interaction.response.send_message(embed=success_embed, ephemeral=True)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\interactions.py", line 526, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\webhook\async_.py", line 191, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.description: This field is required```but if i have roles other than @ everyone then the command will run successfully, not sure why
rare saddle
#

When I try to add a role to all channels and issue permissions, this error appears

forest spear
full valley
#
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, member = None):
    if ctx.channel.id in allowed_channels:
        pid = ctx.author.id
        info = pstats.find_one({"id": pid})
        if info is None:
            embed = discord.Embed(description="You have not played a game yet!", 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)
        else:
            pwins = info["Wins"]
            plosses = info["Losses"]
            pmmr = info["MMR"]
            rank = info["Rank"]
            standing = 0
            rankings = pstats.find().sort("MMR", -1)
            for x in rankings:
                standing += 1
                if info["id"] == x["id"]:
                    break
            embed = discord.Embed(
                title=f"{ctx.author.name}'s stats", color=0xE74C3C)
            embed.add_field(name="Name", value=ctx.author.mention, inline=True)
            embed.add_field(name="Wins", value=f"{pwins}", inline=True)
            embed.add_field(name="Losses", value=f"{plosses}", inline=True)
            embed.add_field(name="MMR", value=f"{pmmr}", inline=True)
            embed.add_field(name="Standing", value=f"{standing}/{ctx.guild.member_count}", inline=True)
            embed.add_field(name="Rank", value=f"{rank}", 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)```
#

token is None

#

clearly not

#

Where is token

versed shuttle
#

You obviously did something to an empty object

#

Remove the parentheses and try again

slate swan
#

it should be

client.run(os.getenv("token"))```

go to secrets create a secret name it token and value it as your token
boreal ravine
#

It does, install master branch or use a fork.

heavy folio
boreal ravine
#

You didnt enter a token

boreal ravine
# heavy folio isnt it optional

I mean yeah but it says In data.embeds.0.description: This field is required error doesnt lie. Maybe something else is causing the error?

#

your supposed to get the key

heavy folio
#

im not sure tho, it worked previously without a description

slate swan
#

my brain it hurts i cant understand anything

boreal ravine
#

not the token

#

@slate swan your supposed to do it like this

key = "your_token" #in the secrets tab

bot.run(os.getenv("key"))
boreal ravine
slate swan
#

Regenerate your token

slate swan
boreal ravine
slate swan
boreal ravine
#

yeah multiple people told him that already

slate swan
#

bot.run(os.getenv("your_actual_token"))

#

Yeah

full valley
boreal ravine
#

hm

#

L

slate swan
#

You have added intents but didnt enabled in developer portal

full valley
#

Idk how I can convert my member argument to an id

boreal ravine
#

the error dont lie

boreal ravine
#

^

slate swan
#

also you literally leaked your token, better reset it real quick

full valley
# slate swan member.id
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, player = None):
    if ctx.channel.id in allowed_channels:
        if player = None:
            pid = ctx.author.id
        else:
            pid =
            info = pstats.find_one({"id": pid})
full valley
#

right, so if they mention someone in the player argument, pid would be there id

full valley
#

and if they mention an id, it will keep it?

slate swan
#

yea

full valley
#

alright tyvm

slate swan
#

πŸ‘ πŸ‘

slate swan
full valley
# slate swan πŸ‘ πŸ‘
File "D:\6Mans\Main\mainwithdict.py", line 135, in stats
    pid = player.id
AttributeError: 'str' object has no attribute 'id'
slate swan
#

You need to convert it to a discord user object first no?

manic wing
full valley
#
@bot.command(pass_context=True, name="stats", description="Check your 6Mans stats")
async def stats(ctx, player = None):
    if ctx.channel.id in allowed_channels:
        if player == None:
            pid = ctx.author.id
            info = pstats.find_one({"id": pid})
        else:
            pid = player.id
            info = pstats.find_one({"id": pid})
            if info is None:
                embed = discord.Embed(description="You have not played a game yet!", 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)
                  ...
slate swan
#

you have player=None

#

But you need to do

#
player:discord.User = None```
#

Convert it to a discord object first yes.

full valley
#

person or player?

#

doesnt matter right

slate swan
#

player i mean

full valley
#

right

slate swan
#

Whatever you are calling it ye

slate swan
#

yea or it would not work

#

It's common in both cases and hence there is no point making python process it twice

full valley