#discord-bots

1 messages · Page 531 of 1

boreal ravine
#

How does the change anything

slate swan
#

when did you install python

boreal ravine
#

what

valid niche
#

That’s a windows CMD right?

honest wing
#

how could I make a stock / setstock command

valid niche
#

Python3 and pip3 are Linux things

boreal ravine
valid niche
#

It’s just python and pip on windows

boreal ravine
#

hm

crystal wind
#

AYYY I FIXED IT

#

The reason why my cogs didn't work is because I made a sorry ladies on "@commands.command" and added something after. This makes all the cogs not working because of that. SO BEWARE.

boreal ravine
#

whats a sorry ladies

hard trail
#

Can someone send me a code on how to assign roles when a command is said for example $verify and then the bot gives the Verified role.

#

I'm just not getting it

boreal ravine
#

How do I create an invite with my bot?

boreal ravine
unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate phoenix
unkempt canyonBOT
#
Out of the question.

No documentation found for the requested symbol.

boreal ravine
#

TextChannel

slate phoenix
#

yeah thats my bad i mistyped

honest wing
#

how could I make a stock / setstock command

set stock would set a variable for example: '2 billion'
stock would return 2 billion

slate phoenix
boreal ravine
#

cool thanks

slate swan
honest wing
#

literally all i want to do is set the stock to a variable and then send iot using stock command

honest wing
#

bro ok so variable would return "2 billion", and then setstock could change that to "1 million" and it would return 1 million

wintry lintel
#

So you need something that can process text representations of numbers?

honest wing
wintry lintel
honest wing
#

wait no nvm

#

that isnt what i mean

wintry lintel
#

Ok

honest wing
#

This what I mean, .stock would return 1 billion though.

Also a setstock that could change the 1 billion to 14 million, etc.

honest wing
final iron
#

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

honest wing
#

LOL??

#

Are you serious

final iron
#

Yes

steel trench
#

broment

honest wing
#

Skyblock coins don't break discord TOS deadbeathyper

slate swan
#

that doesnt break anything

final iron
#

@wintry lintel I would suggest you do not help this man anymore

steel trench
#

bro what

final iron
honest wing
#

ok and?? not discord tos

wintry lintel
#

Still kind of sketch

final iron
#

It doesn't say discord tos

#

It says "terms of services"

#

With the plural this implies any tos

honest wing
#

ok report me?? i dont care

#

idk why ur so mad

final iron
#

Im not mad

slate swan
final iron
#

I'm just trying to keep you from getting punished

final iron
honest wing
final iron
#

Irl trading

slate swan
#

it says as long as it doesnt boost the players its fine

honest wing
#

Not selling the coins for IRL money, for other items in skyblock

final iron
#

Fr bro

honest wing
boreal ravine
#

why is everybody's fav word here "braindead"

honest wing
boreal ravine
final iron
honest wing
final iron
#

Invite me to the one you're testing the bot in

honest wing
#

Why should I?

slate swan
final iron
#

So you can prove that it's not for irl trading

honest wing
final iron
#

It is against the server rules though

honest wing
#

Not irl trading, dont have to worry about it

final iron
#

Doubt

honest wing
#

doubt me all you want, i dont care

final iron
#

No need for insults

honest wing
visual yarrow
#

!ban 875478020884926526 Racial slur directed at another user.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @eager forge permanently.

honest wing
#

@final iron Do you actually help people or do you sit here waiting for someone to break TOS so you can report them? Holy fuck it's annoying.

final iron
#

Oh yeah I forgot that was a slur

#

Huh

honest wing
#

Just asked for help simply and you sit here waiting for me to break a rule

final iron
#

!topic

unkempt canyonBOT
final iron
#

^

honest wing
#

You started it

slate swan
#

maybe if you explain what your doing that would clear things up

final iron
#

Yell at me in there

honest wing
#

¯_(ツ)_/¯

honest wing
slate swan
#

well say it again

final iron
#

Can we see your commands?

honest wing
final iron
#

Look you can argue all you want but it's pretty obvious this is an irl trading shop

honest wing
final iron
visual yarrow
#

!silence

unkempt canyonBOT
#

✅ silenced current channel for 10 minute(s).

visual yarrow
#

!mute 884211706581098507 It's not acceptable to talk to to other members of this server in this way.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @honest wing until <t:1634011454:f> (59 minutes and 59 seconds).

visual yarrow
#

@final iron Please report issues to the mods via @novel apex

#

!unsilence

unkempt canyonBOT
#

✅ unsilenced current channel.

final iron
#

Alr will do

slate swan
#

anyway now that thats done

final iron
#

It is

#

He started dming me racial slurs so I dmed mod mail

slate swan
#

ima put it in general

maiden fable
#

No need to

#

But it would be self.bot.process_commands

boreal osprey
boreal osprey
#

it would spam the message that i want the bot to respond with

maiden fable
#

BTW nice token u got there @boreal osprey

boreal osprey
#

FUCK

maiden fable
#

Haha it's okay

#

Just reset it

#

(That just came to my mind, so told u)

boreal osprey
#

THANKS FOR TELLING ME OMG

maiden fable
#

(:

boreal osprey
#

i actually freaked out lmfao

maiden fable
#

Haha it's fine.

boreal osprey
#

@maiden fable btw i still get the error

maiden fable
#

Yes

#

Just remove that line. If u process commands inside a cog, then the bot would reply to a command twice

maiden fable
#

Can I get some code?

boreal osprey
#
@commands.Cog.listener()
    async def on_message(self, message):
        if "hi" in message.content:
            message = message.channel
            await message.send("hiiii")
#

i'm new to cogs so it's kinda confusing on what to do

pliant gulch
#

You aren't returning if the message's author is from the bot

gloomy coral
#

Hi

#

I need help with slash commands

#
@cog_ext.cog_slash(name="makerole"
        , description="Makes a new role in the server for you!"
        , options=[create_option(name="rolename"
            , description="Name of the role you want to make.",
                                 option_type=3,
                                 required=True
                                 )
                   ]
                       )
    async def _makerole(self, ctx: SlashContext, rolename: str):
        color = discord.Color.random()
        if ctx.author.guild_permissions.manage_roles:
            guild = ctx.guild
            perms = discord.Permissions(send_messages=True, read_messages=True)
            role = await guild.create_role(name=rolename, color=color, permissions=perms)
            embed1 = discord.Embed(title="Role Created!",
                                   description=f"Added role {role.mention} to the server!",
                                   color=color)
            embed1.set_footer(text=f"Tip: Do {ctx.prefix}addrole to add your newly created role to users!")
            await ctx.send(embed=embed1)

        else:
            await ctx.send(
                embed=discord.Embed(title="Stop right there!",
                                    description="You require the Manage Roles permission.",
                                    color=color))```
pliant gulch
gloomy coral
#

Here it shows ```py
embed1.set_footer(text=f"Tip: Do {ctx.prefix}addrole to add your newly created role to users!")
AttributeError: 'SlashContext' object has no attribute 'prefix'

boreal osprey
pliant gulch
errant shuttle
#

hey how do i get the mentioned member's server nickname in discord.py?
Rich now my member parameter is giving member_user#member_discriminator
here is my code

async def nick(ctx, member : discord.Member, *, message):
gloomy coral
#

Help me pls

errant shuttle
boreal osprey
maiden fable
#

Or member.nick

errant shuttle
valid perch
#

Go view le docs attrs then

#

!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.
gloomy coral
maiden fable
#

Slash commands

errant shuttle
gloomy coral
#

then what can i do?

boreal ravine
#

you can do it manually

waxen granite
#

How do i get the member who deleted the msg?

#

Not message.author

boreal ravine
waxen granite
#

Not other way?

boreal ravine
#

dont think so

#

!d discord.AuditLogAction.message_delete

unkempt canyonBOT
#

A message was deleted by a moderator. Note that this only triggers if the message was deleted by someone other than the author.

When this is the action, the type of target is the Member or User who had their message deleted.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

count: An integer specifying how many messages were deleted.

channel: A TextChannel or Object with the channel ID where the message got deleted.

maiden fable
#

Use on_raw_message_delete or something

gloomy quest
#

How to make it so that if someone messages the bot then it will do smething like say Hello

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
dapper cobalt
#

Check if the message.guild is None.

#

!d discord.Message.guild

unkempt canyonBOT
wintry lintel
#
@bot.on_message
def on_message(ctx):
    ctx.send('hello')
dapper cobalt
#
@bot.event
async def on_message(message):
  if not message.guild:
    await message.channel.send("Hello")
wintry lintel
#

oh wait asynchronous functions sorry

dapper cobalt
#

There's no such thing as @bot.on_message.

#

And why did you pass ctx?

#

You should pass message not ctx.

gloomy quest
#

can I use bot.listen()?

dapper cobalt
#

Yes.

wintry lintel
#

When inherits from discord.Client, you can set function on_message

dapper cobalt
#
@bot.listen("on_message")
async def my_message_event(message):
  if not message.guild:
    await message.channel.send("Hello")
gloomy quest
#

K thx

#

it loops hello

sick wedge
#

anyone know how to make a message if the user is dont have a permission using the specific command

boreal ravine
#

many ways to do it but idk

sick wedge
#

can i do with if state?

#

or any idea?

slate swan
#

GuYs How to make my discord bot say Bad human when someone says bad bot in chat? Me have no coding experience. What code gibberish do i type to make it do that? I read the beginner discord bot tutorial and me no get.

grim oar
#

i would suggest learning python first since making discord bots is not beginner friendly

slate swan
#

i kinda wanted it to be just a funny bot that all it does is say nope and no to every message

#

kinda like a useless joke bot

#

You should still start by learning Python before doing it

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

boreal ravine
boreal osprey
slate swan
#

No not at all

trim briar
# slate swan Stinky:( that take years to learn

See if you understand how python works, how does it print this when we type this, you start understanding the concepts then it will reduce your amount of time needed for learning python. It's very easy and straight-to-the-point language compared to other programming languages.

slate swan
#

oh ok

trim briar
slate swan
#
@bot.command(pass_context=True)
async def test(ctx, user: discord.Member):
    hypesquad_class = str(user.public_flags.all()).replace('[<UserFlags.', '').replace('>]', '').replace('_',
                                                                                                         ' ').replace(
        ':', '').title()
    
    hypesquad_class = ''.join([i for i in hypesquad_class if not i.isdigit()])

    test = discord.Embed(title=f"{user.name} User's Badges", description=f"{hypesquad_class} {nitro} {staff} {partner} {bug_hunter} {early_supporter} {team_user}", color=0x2f3136)
    await ctx.channel.send(embed=test)```
is there any way i can adjust this to work for all the flag pull requests ive put? i know they arent defined, but ive taken the flags from https://discordpy.readthedocs.io/en/latest/api.html?highlight=profile#profile and i just dont know how to make it work
lament mesa
#

Why are you using str.replace?

slate swan
#

You know that [<UserFlags....>] indicates it's a list of UserFlags objects right?

lilac latch
#

from discord import egirls

#

Interesting

#

xD

slate swan
boreal ravine
lilac latch
boreal ravine
#

copying code cringe

slate swan
#

And in addition to that, to check if a user has a flag/badge simply use, for example

user.public_flags.staff
trim briar
#
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 209, in on_raw_reaction_add
    if payload.member.bot:
AttributeError: 'NoneType' object has no attribute 'bot'
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 209, in on_raw_reaction_add
    if payload.member.bot:
AttributeError: 'NoneType' object has no attribute 'bot'

I don't know what's wrong here

slate swan
#

intents

#

you're 100% missing intents

trim briar
#

oh yeah

#

I put em in the commands.Bot?

boreal ravine
#

do intents = discord.Intents.all()

boreal ravine
trim briar
#

oh alright

slate swan
slate swan
boreal ravine
unkempt canyonBOT
#

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

!subscribe

slate swan
#

How do I print bot's roles, I tried this but not working....py @client.command() async def roles(ctx): for role in client.roles: await ctx.channel.send(role)

#

Define "not working"

slate swan
#

Yes

lament mesa
unkempt canyonBOT
#

property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
slate swan
#

As it gets the roles of me which is the logged in client aka bot

#

actually I want to print my bot's roles

lament mesa
#

your roles or the bots?

slate swan
#

bots

#

bot's

#

actually i did this ```py
@tasks.loop(seconds=31)
async def repeat():
for guild in client.guilds:
if guild.id==guildid:
for role in client.roles:
if role.name.startswith('PHG') or role.name.startswith('Ally'):
return
else:
if not role.name in role_name:
for channel in guild.channels:
if channel.id==channelid:
await client.send(channel, "Test")

@client.event
async def on_ready():
print("Connected to {client.user}")
repeat.start()```

lament mesa
#

guild.me.roles to get the bot's roles

slate swan
#

thx I dont need to define me right?

lament mesa
#

what?, me is an attribute of discord.Guild

slate swan
#

Can give me some more examples where I can use me

#

not from this program....just command examples

lament mesa
#

Similar to Client.user except an instance of Member. This is essentially used to get the member version of yourself.

slate swan
#

o thx

#

😄

#

Cuz me know Zip about python and stuff will someone be willing to make a bot for me that says Bad human when someone says bad bot, and when someone says .ask bot <stuff> it will say no and nope?

#

Me need someone to do for me cuz i know 0️⃣ coding

#

This is not a place to hire devs, go to Fiverr for that

#

no me not hire

#

that break rule

#

i mean for free cuz am dumb

#

All we can do is help you with the issues you face

#

And to learn Python there are multiple resources

lament mesa
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

dim cedar
#

!e resourses

unkempt canyonBOT
#

@dim cedar :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'resourses' is not defined
dim cedar
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

slate swan
#

Already gave him that NotLikeThis

slate swan
#

me no get anything

#

Then don't make a custom bot and use existing bots

#

We won't code for you and this is not the place to hire developers

#

ok

gloomy quest
#

im getting an error

#
@client.command()
async def say(ctx, arg):
  if ctx.channel.type is discord.ChannelType.private:
   modmail_channel = discord.channel.id(int(897362022960861224))
   embedmodmail = discord.Embed(title="New message", description=f"{ctx.author}: {arg}", color=0x1dddee)
   await modmail_channel.send(embed=embedmodmail)
  else:
    return
#

In it it says discord.channel has no attribute id

lament mesa
#

discord.channel is a module

gloomy quest
#

then

slate swan
#

get_channel

gloomy quest
#

discord.get_channel?

lament mesa
#

no

slate swan
#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.
gloomy quest
#

/?

slate swan
#

Read the docs

lament mesa
slate swan
#

Click on the link

#

Oh haven't seen there's also something like that above

#

I was looking at the discord.channel.id()

gloomy quest
#

Its like modmail

#

It sends what u say

slate swan
#

Then it's discord.ext.commmands.Bot.get_channel

gloomy quest
#

k

slate swan
#

And don't just copy paste it

gloomy quest
#

Ohhh

slate swan
#

Use your bot instance variable

lament mesa
#

!d discord.Client.get_channel

unkempt canyonBOT
gloomy quest
#

client.get

waxen granite
#

Can someone teach me breaking a msg content in cases where the content characters limit exceeds 4000 in normal and 6000 in embeds?

gloomy quest
#

o

#

discord.ext has no attribute commands

#

BUT HOW

#

how is that possible

waxen granite
boreal ravine
#

code?

gloomy quest
#

hmm

gloomy quest
boreal ravine
#

with open ("okay.exe", "a+") as f:

errant shuttle
#

Hey I want to kick someone in discord.py with the click of a button but it says interaction failed
here is my code

from discord import *
from discord.ext import commands
from discord_buttons_plugin import *

@buttons.click
async def kickbtn(ctx, member : Member, *, reason):
    await member.kick(reason = reason)
    await ctx.send(f"Successfully kicked {member} because {reason}")

@buttons.click
async def nokickbtn(ctx):
    await ctx.send("Phew")

@client.command(aliases=['lolkick', "remove", "yeet"])
async def kick(ctx, member : Member, *, reason = "No particular reason"):
    if ctx.message.author.guild_permissions.administrator or ctx.message.author.guild_permissions.kick_members:

        await buttons.send(
            content = f"Kick {member} because {reason}?",
            channel = ctx.channel.id,
            components = [
                ActionRow([
                    Button(
                        style = ButtonType().Danger,
                        custom_id = "kickbtn",
                        label = "YES!",
                    ),

                    Button(
                        style = ButtonType().Primary,
                        custom_id = "nokickbtn",
                        label = "No",
                    )
                ])
            ]
        )

What is wrong here?

#

^what is wrong with that piece of code?

glad sleet
#
buttons = [
  [
    Button(style=ButtonStyle.grey, label="1"),
    Button(style=ButtonStyle.grey, label="2"),
    Button(style=ButtonStyle.grey, label="3"),
    Button(style=ButtonStyle.blue, label="×"),
    Button(style=ButtonStyle.red, label="EXIT"),
  ],

  [
    Button(style=ButtonStyle.grey, label="4"),
    Button(style=ButtonStyle.grey, label="5"),
    Button(style=ButtonStyle.grey, label="6"),
    Button(style=ButtonStyle.blue, label="÷"),
    Button(style=ButtonStyle.red, label="←"),
  ],

  [
    Button(style=ButtonStyle.grey, label="7"),
    Button(style=ButtonStyle.grey, label="8"),
    Button(style=ButtonStyle.grey, label="9"),
    Button(style=ButtonStyle.blue, label="+"),
    Button(style=ButtonStyle.red, label="CLEAR"),
  ],
  
  [
    Button(style=ButtonStyle.grey, label="00"),
    Button(style=ButtonStyle.grey, label="0"),
    Button(style=ButtonStyle.grey, label="."),
    Button(style=ButtonStyle.blue, label="-"),
    Button(style=ButtonStyle.green, label="="),
  ],
]

def calculator(exp):
  o = exp.replace('x', '*')
  o = o.replace('÷', "/")
  result=""
  try:
    result = str(eval(o))
  except:
    result="An error occurred"
  return result

@bot.command()
async def calc(ctx):
  m = await ctx.send(content="Loading Calculator")
  expression = 'None'
  delta = datetime.datetime.utcnow() + datetime.timedelta(minutes = 5)
  
  e = discord.Embed(title=f'{ctx.author.name}\'s | {ctx.author.id}',description=expression,timestamp=delta)
  await m.edit(components=buttons, embed=e)
  while m.created_at < delta:
    res = await bot.wait_for('button_click')
    if res.author.id == int(res.message.embeds[0].title.split('|')[1]) and res.message.embeds[0].timestamp<delta:
      expression = res.message.embeds[0].description
      if expression == 'None' or expression == 'An error occurred':
        expression = ''
      if res.component.label == 'EXIT':
        await res.respond(content="Calculator closed", type=7)
        break
      elif res.component.label == '←':
        expression = expression[:-1]
      elif res.component.label == 'CLEAR':
        expression = None
      elif res.component.label == '=':
        calculator(expression)
      else:
        expression += res.component.label
      f = discord.Embed(titile=f'{res.author.name}\'s calculator|{res.author.id}', description = expression,timestamp=delta)
      await res.respond(content="", embed=f, component=buttons, type=7)```
#

i use this for button calculator but interaction fail

stark bobcat
#

hlo

#

what does ctx.author.status do

lament mesa
#

!d discord.Member.status

unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
stark bobcat
lament mesa
#

yeah, and it can be a string

stark bobcat
#

ok

#

thanks

boreal ravine
stark bobcat
tawdry perch
#

maybe status not Status

lament mesa
#

lowercase s

stark bobcat
#

oh

#

ok thanks

boreal ravine
# stark bobcat

i think only the class names are uppercase (discord.Guild, discord.Member) and the rest are lowercase

lilac latch
#

Hmm how to check which song is being played by the user??

#

On spotify

boreal ravine
unkempt canyonBOT
#

class discord.Spotify```
Represents a Spotify listening activity from Discord. This is a special case of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that makes it easier to work with the Spotify integration.

x == y Checks if two activities are equal.

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

hash(x) Returns the activity’s hash.

str(x) Returns the string ‘Spotify’.
boreal ravine
#

check if the user

#

has a spotify activity

silk goblet
#

How can i make a command proposal by entering a / and then see all of the possible commands?

#

i mean that i type / in the discord chat and then there is a pop up which showes that i have the option to enter for example /help

slate swan
#

These are so called slash commands

stiff nexus
#

help??```py
permissions = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])

i cant get like:
`Add Reactions`, `View Audit Log, Stream`, `Read Messages`, `Send Messages`, `Embed Links`, ..... ????
tawdry perch
#

and what is wrong? Telling that may help

tawdry perch
#

this channel has become very quiet lately

slate swan
#

But is it really that bad?

tawdry perch
slate swan
#

yikes

#

@tawdry perch it's your moment

tawdry perch
#

?

slate swan
tawdry perch
#

I'm in middle of class 😅

surreal sierra
#

Hey, how would you make a bot send a msg everyday at a specific time for example 1 PM everyday?

tawdry perch
#

!tasks.loop

#

uuh

surreal sierra
#

...

tawdry perch
#

anyways, use tasks.loop

surreal sierra
#

okay XD

#

ty

tawdry perch
#

@surreal sierra this takes a well time argument

surreal sierra
#

thx!

tawdry perch
#

Np, if it is still unclear I can send a example of usage

cloud dawn
tawdry perch
#

sadly

#

I'm 100% not lurking here

cinder horizon
#
"server id": "s/", ">",
```how do i do this
cloud dawn
#

Were not going to explain json inside an async wrapper.

unkempt canyonBOT
cloud dawn
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

mmmk

#

You know there are libraries to read JSON in an asynchronous way right

#

it's called aiofiles

cloud dawn
#

aiofiles is like your last resort if you need to do it. Here there are numerous other variations.

pliant gulch
#

You won't need an extra dependency

#

Just do all the file opening stuff in executor

#

Shouldn't block the loop

cloud dawn
#

Does block your code

#

The point is it's the file that will block the code, for loops also block the code but for a short while. He is putting server id's inside the json and then json take long to load even with a mere 200 servers. For configs it's okay.

pliant gulch
vocal plover
tawdry perch
#

the docs?

cloud dawn
pliant gulch
#

Do you know that won't matter much

#

I mean the docs for running in executor even show a file open

cloud dawn
#

reference?

pliant gulch
#

I mean, you can even try it yourself lmao, Idk how you would say that would block

cloud dawn
#

Okay true this could solve blocking now that i see it. But still loading json over 200kb takes long. I don't get why you would go trough all of this trouble whilst things like db's got invented.

pliant gulch
#

I don't really think speed matters here, the point is that it won't block and thus you can still do things while its loading

heavy folio
#

hi, so if im using args.split(","), how do i check if the message has 4 ,s or not?

cloud dawn
#

!e print("Hello, world".count(','))

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

1
heavy folio
#

oh ty

cinder horizon
#
@bot.command()
async def test(ctx):
  if ctx.author.status.dnd:
    await ctx.send("meh")
```welp no errors ntng...wt do i do?
maiden fable
#

Cz there should be no error....?

cloud dawn
#

What does ctx.author.status.dnd return?

#

False or True i assume

maiden fable
#

!d discord.Status.dnd

unkempt canyonBOT
maiden fable
#

Yea

cinder horizon
maiden fable
#

Huh?

#

I mean, the code is different than the error. Restart the bot

cloud dawn
#

Do you got the traceback for us?

maiden fable
#

I mean, I can see it. In the exception, it's Status, not status lol

cinder horizon
maiden fable
#

Heh

cinder horizon
#

welp

boreal ravine
maiden fable
#

Ah yea. U should do that

cinder horizon
#

oki

pliant gulch
#

== is used to check if the value is the same

#

You should be using is here

boreal ravine
#

hm

cinder horizon
#

works

#

thenks

cloud dawn
#

isn't is getting deprecated in 3.10?

boreal ravine
#

huh

#

it is?

normal ore
pliant gulch
boreal ravine
heavy folio
normal ore
heavy folio
boreal ravine
cloud dawn
heavy folio
#

pip install discord_build_info_py

normal ore
#

done

boreal ravine
dim cedar
#

Is there any way to make a translation cmd in my discord bot without googletrans API

normal ore
cloud dawn
#

I mean google is not the only translator

dim cedar
cloud dawn
#

Google Translate
Microsoft Translator
Yandex Translate
Promt Translator
Pragma Translator
Baidu Translator
Naver Translator
Sogou Translator
Systran Translate
Babylon Translator
Dictionaries by Babylon
Lingvo Dictionary
Glosbe Translator
Urban Dictionary
IBM Translator
Apertium Translator
DeepL Translator

dim cedar
#

Oh m g

dim cedar
cloud dawn
#

I have no idea

boreal ravine
boreal ravine
cloud dawn
#

You can also just use them all and allow the user to choose :)

boreal ravine
#

it's a shitpost website

cloud dawn
heavy folio
#

if i have a command cooldown, how do i get the user's cooldown timing left in 3 digits (e.g. 1.23)

boreal ravine
#

it's a float by default

#

oh

heavy folio
#

ohh okay ty

cloud dawn
# boreal ravine hm

You cannot choose the languages though i think it gives you like the 5 most spoken languages and also their meaning.

boreal ravine
#

wait

dim cedar
#

Results come for google trans api

dim cedar
#

Can u tell me in the dm how to use that to make a translation cmd

#

Short tutorial

boreal ravine
#

no

#

read the api's docs and you'll know how to do it

cloud dawn
#

No it's a general API works like every other API, make a request using aiohttp with a token and done. If you are lucky someones has made a wrapper.

dim cedar
#

Oh

#

Didnt thouht about that tho

slate swan
#

trying to make a requests with aiohttp??

#

uhm and i was just gonna ask do you think that's fast enough for an anti-nuke?? using aiohttp

slate swan
#

wym

#

ik i'm using a lib inside aiohttp i just can't remember which one

final iron
slate swan
#

iirc?? not very understanding of python

final iron
#

That has nothing to do with python

#

That is just my memory

slate swan
#

i'm a rust/ruby coder never seen the term "iirc" before

pliant gulch
#

How would the wrapper be faster then making a request via aiohttp

valid perch
#

Should be fine, times will vary regardless

#

iirc -> if I recall correctly

Tis not a pythony thing

valid perch
slate swan
#

that's what i use ClientSession

valid perch
#

Request times will be different per request anyway, tis the nature of the internet

pliant gulch
#

Well, if you just use aiohttp you cut out all the library abstraction all the objects, etc

#

you go straight to the API

valid perch
#

Like I said, thats my guess. Otherwise idk, and I'm not in the mood to profile it

steep estuary
#

how i can take both id and discord.Member here ??

async def ban(ctx, member: discord.Member and id) 
``` ??
boreal ravine
unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
boreal ravine
#

idk how to convert a member obj into an ID tho

pliant gulch
#

What they have currently takes an ID alr

steep estuary
#

?

pliant gulch
#

Typehinting discord.Member runs the member converter

steep estuary
#

where to use memberconverter?

#

membre: memberconverter?

pliant gulch
#

You are already using the member converter

boreal ravine
#

yeah, but how do you ban someone using ID but using discord.Member?

pliant gulch
#

....? You pass the ID

pliant gulch
#

Says lookup via ID

boreal ravine
#

but thats for commands.MemberConverter you said you can already use id using discord.Member?

pliant gulch
#

typehinting discord.Member runs the member converter

boreal ravine
#

hm

pliant gulch
#

Literally discord.py reads the parameters typehint annotations

#

Runs it through a converter mapping

#

then grabs the corresponding converter

boreal ravine
#

hmm thanks for explaining I didn't know that

slender pollen
#

Hello, I'm making discord game with 4 players. How can I make the bot to send whose turn is?

visual island
pliant gulch
#

Why not

#

Its not to import things, its for typechecking

#

And getting an import you want to typehint without importing it really

visual island
# pliant gulch Why not
    self.params[key] = value = value.replace(annotation=eval(value.annotation, function.__globals__))
  File "<string>", line 1, in <module>
NameError: name 'Context' is not defined

# imports
from __future__ import annotations

if TYPE_CHECKING:
  from ext.context import Context  # a custom context
# The command

@bot.command()
async def command(ctx: Context):
    ...
steep estuary
#

:/

visual island
#

It doesn't, really

#

and string typehints also

slender pollen
pliant gulch
#

Since its a custom context you actually need to import this

visual island
pliant gulch
#

Yes

#

As you can see from the error

visual island
#

why tho, making a custom Context without overriding get_context isn't possible. But why do they need to eval Context?

pliant gulch
#

Not sure why they do it ¯_(ツ)_/¯

visual island
pliant gulch
#

In my wrapper I just skip the first parameter

slate swan
#

help anyone i am making error command for Youtube together and it needs you to join a voice channel first so what should be the error

surreal sierra
visual island
boreal ravine
slate swan
boreal ravine
slate swan
boreal ravine
#

but its the simplest way to catch errors

boreal ravine
slate swan
boreal ravine
slate swan
#

@boreal ravine

#

commands. ____?

boreal ravine
#

i dont know

#

look at the exceptions

heavy folio
#

hi, so i have this command https://paste.pythondiscord.com/ejulumepig.properties, and when the user didnt include anything in options, the bot did the right actions, when the user included less than 4 commas in the arg options, the bot would do what it should do, same for when there are more than 4 commas in options, but when the user included exactly 4 commas, it did what the bot would do when there are less than 4 commas, did i do anything wrong? the bot should be doing whats stated in the last if statement

lilac latch
tawdry perch
lilac latch
#

I did that

burnt warren
#

Can someone give me a comparison on using flask vs quart for executing bot commands?

waxen granite
#
    async def connect(self, ctx: commands.Context):
        """Connects the bot to a voice channel."""

        if ctx.author.voice is None:
            embed = discord.Embed(description = "**:alert:You have to join a voice channel to use this command. **", color = discord.Colour.random())
            return await ctx.send(embed = embed)
        try:
            destination = ctx.author.voice.channel
            print("1")
        except:
            if self.bot.user.destination_permissions.connect is False:
                return await ctx.send("cant connect you channel")
        voice = get(ctx.bot.voice_clients, guild=ctx.guild)```
how can i return the bot if the destination channel perms for connect is False for the bot? and send a msg while returning?
slate swan
#

This bot

#

I swear to god

high flame
visual island
#

just for typehinting purposes

#

allows you to use string for typehints

high flame
#

example?

visual island
#

and

class Foo:
     def a(p: Foo):
         ... 

```raises NameError, but with annotations works fine
visual island
high flame
#

k

shell wing
#

I have a list of user ids in .json how do i DM those users after a time interval ?

slate swan
#

Create a task loop that reads the JSON and it's content and then get a user object based on the ID you've gathered from reading the file and use .send() on it

shell wing
slate swan
#

No

#

All of that is basically wrong

#

And you should use a database for this kind of work not a JSON file

shell wing
#

    @commands.command()
   
    async def work(self, ctx):
      ID = ctx.author.id
      with open("worker.json", "w") as f:
                json.dump(ID, f, indent=4)
       
      await ctx.send("done")
      self.bot.loop.create_task(dms(ctx, username))

    @commands.command()
    async def dms(self, ctx, user):
      ID = ctx.author.id
      with open("worker.json", "r") as f:
                json.dump(ID, f, indent=4)
      for user.id in worker.json:
        await user.send("ok")
        break
shell wing
# shell wing ```py @commands.command() async def work(self, ctx): ID = ctx...
Ignoring exception in command dms:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: user is a required argument that is missing.
slate swan
#

U can use sqlite, xampp, wamp

shell wing
ripe jackal
#

Hello, I am trying to create a lil more advanced audit logger, but I got an error. What should I do? This is the error ``` on_ready
self.bot.cogs_ready.ready_up("logs")
AttributeError: 'AutoShardedBot' object has no attribute 'cogs_ready'

This is the code: ```python
    @Cog.listener()
    async def on_message_delete(self, message):
        if not message.author.bot:
            embed = Embed(title="Message deletion",
                          description=f"Action by {message.author.display_name}.",
                          colour=message.author.colour,
                          timestamp=datetime.utcnow())
            fields = [("Content", message.content, False)]
            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)
            await self.log_channel.send(embed=embed)```
#

And this is the on_ready event from the errorpython @Cog.listener() async def on_ready(self): self.log_channel = self.bot.get_channel(896848647638114474) self.bot.cogs_ready.ready_up("logs")

slate swan
#

'AutoShardedBot' object has no attribute 'cogs_ready'

#

cogs_ready is not a thing in the library

ripe jackal
slate swan
#

Well don't use it

#

That's probably code from another bot

ripe jackal
slate swan
#

Yup it is

#

Don't copy paste thanks

#

and don't forget to change the log channel id CS_kekw

ripe jackal
#

It was too hard for me so I watched a youtube video about it...

#

see

#
on_message_delete
    await self.log_channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
#

this is the error I got from the event

#

How should I repair that?

#

oh nvm, I got it

slate swan
#

Well as I said, change the id CLk_KekW

glad thicket
#

i have a question how do i have access to other peoples bots and add them to a server

slate swan
#

You don't have access to the bots you can use them

#

With an invite url

glad thicket
#

ok

burnt warren
#

Can someone give me a comparison on using flask vs quart for executing bot commands?

glad thicket
#

how do i find the "invite url"?

slate swan
#

Bots have commands

#

Probably a help command

burnt warren
#

Okay, I want to use a URL to execute bot commands

slate swan
#

I'd say Quart then, it's faster at handling lots of request

#

And since you should expect to be spammed from requests by bots and scripts, you need something to handle them faster

#

I definitely don't recommend to make commands executable from a url

#

No wonder why nobody never really did it

quasi pawn
#

What's the diff between @commands.command and @bot.command?

lament mesa
#

wait, nvm

#

!d discord.Message.role_mentions

unkempt canyonBOT
slate swan
#

It returns a list of Role objects

#

And roles objects have the id attribute

lament mesa
#

it is a list of discord.Role objects, you can do Role.id

slate swan
unkempt canyonBOT
slate swan
#

nextcord.Message represents your message object

#

role_mentions returns a list so your need to loop or iterate through it

#

And don't forget to learn Python before doing a bot

pliant compass
#

How can I get a;l members in a guild? I have tried this code:

guild = client.get_guild
for member in guild.members:
    print(member)
```This is the error that I get:

'function' object has no attribute 'members'

slate swan
#

!d discord.Client.get_guild

unkempt canyonBOT
slate swan
#

As you can see it requires an ID as parameter

autumn bone
#

Hello, i try to use "member.locale", but i have an error message :

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/pi/mon_dossier_partagé/BOT_Discord/JLEBot/WIP2.py", line 20, in on_ready
    getInfoOnMember()
  File "/home/pi/mon_dossier_partagé/BOT_Discord/JLEBot/initFunction.py", line 314, in getInfoOnMember
    print(member.locale)
AttributeError: 'User' object has no attribute 'locale'

Code :

    member = bot.get_user(281165062041894914)
    print(member.locale)
boreal ravine
#

Whats member.locale supposed to mean?

autumn bone
#

"The IETF language tag used to identify the language the user is using."'

boreal ravine
#

i dont think u can detect that using a bot

autumn bone
#

avatar, avatar_url, etc... work, so ^^

boreal ravine
#

they return the members avatar?

#

hm

dapper cobalt
autumn bone
#

1 : avatar
2 : if bot
3 : username

dapper cobalt
#

I think it's for only user accounts, aka, self-bots.

boreal ravine
#

yeah thats what I was saying

autumn bone
#

So there is no way to get the user's language?

boreal ravine
slate swan
#

Bots have this attribute

autumn bone
#

Because in Discord API, it's in deployed ^^

boreal ravine
#

hm

slate swan
#

Pretty sure it's the same as the owner of the bot

autumn bone
slate swan
#

You only get that for the current user

#

Would be too nice to know if a random user has mfa enabled huh

boreal ravine
#

whats mfa

slate swan
#

Multi-factor authentication

#

2fa, sms, etc.

boreal ravine
#

ohh

autumn bone
#

It's available in Discord Developpers documentation

#

And in Discord.JS

slate swan
#

Again

#

For current user

#

Or if you have the oauth

#

Which you don't

#

Bots can get their locale with /user/@me endpoint

#

pretty sure it's the bot owner's locale

#

And as a bot getting to the /user/id endpoint doesn't give it

#

So no, you can't get any user's locale

mild zephyr
#

what lib should i use to make a good discord bot?

lament mesa
mild zephyr
boreal ravine
#

wait if we use dpy v1.7 < will we be able to use the deprecated methods?

lament mesa
lament mesa
boreal ravine
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

boreal ravine
#

hm basically sending FR's to a member

lament mesa
#

thats for self bots

boreal ravine
#

using a bot

boreal ravine
lament mesa
#

no, bot accounts cant have friends

boreal ravine
#

hm

lament mesa
boreal ravine
#

o

#

how did people implement it into a non-bot account though?

lament mesa
#

you cant

boreal ravine
#

hm

dapper cobalt
#

!d discord.Guild.get_role

unkempt canyonBOT
indigo thunder
#

Hi guys, How to make discord music codes? With discord.py pls

boreal ravine
slate swan
#

We don't code for you

#

We help you with your issues

#

And music bots are getting shutdown by YouTube, so you might want to reconsider it

boreal ravine
#

896217879387734056 sus account

indigo thunder
slate swan
#

np

dapper cobalt
#

Also, keep in mind that we cannot help you if you're using music sources that do not allow using them in that way.

#

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

indigo thunder
slate swan
dapper cobalt
indigo thunder
slate swan
#

Double ping in one message CS_kekw

dapper cobalt
#

It returns a discord.Role object. Now you figure it out.

#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
dapper cobalt
#

get_role returns a discord.Role object.

#

discord.Role has a name attr.

unkempt canyonBOT
dapper cobalt
#

Please consider clicking the blue title of those embeds. They redirect you to that certain object in the documentation's website, where you can find answers to most of your questions.

slate swan
#

I want my bot to duplicate a role, I did this: py @client.command() async def copyrole(ctx, role_id: int): for role in ctx.guild.roles: if role.id == role_id: await ctx.guild.create_role(name=role.name, colour=role.colour)

What about the permissions??

dapper cobalt
#

Always check the docs before asking.

#

One second.

#

I will ask you a question.

#

What is role_id?

slate swan
#

me?

dapper cobalt
#

Alright. So the ID is a number, right?

#

So let's say the ID is 123. What do you expect to happen if you do 123.name?

#

Yes, it will error.

#

You need to get the role first. And then get the name of it.

slate swan
dapper cobalt
#

Change role_name to role and then do role_name = role.name.

dapper cobalt
unkempt canyonBOT
dapper cobalt
slate swan
#

like py perms=role.permissions

like this?

dapper cobalt
slate swan
#

thx

dapper cobalt
#

Can you show your code?

#

The role does not exist in the guild.

boreal ravine
#

i see useless variables

lament mesa
#

it does not exist or it is not cached

dapper cobalt
#

ctx.author.guild.id though?

tough wagon
#

Does on_command work like this?

@Cog.listener()
async def on_command(self, ctx):```
dapper cobalt
#

Why not just ctx.guild? Or why not use it straight away without defining guild_id?

boreal ravine
tough wagon
boreal ravine
dapper cobalt
#

I thought that was @Bot.listener(), my bad.

tough wagon
boreal ravine
boreal ravine
#

oh

dapper cobalt
lament mesa
boreal ravine
boreal ravine
#

oh

tough wagon
boreal ravine
#

self, ctx then?

surreal sierra
#

Hey, I have been trying to make a command that pings you at given time. So you use the command ?remind 12pm for example and then I want the bot to ping the user everyday at 12 pm.

I had no idea how to do this but this is what I tried and of course it didnt work

@bot.command()  # Help command, command list
async def remind(ctx, clock=None):
    if clock is None:
        remindbed = discord.Embed(title=f"Sorry there has been an error",
                                  description=f"There was no given time when you want to be reminded. ``?remind <time_zone> <clock>``",
                                  color=discord.Color.purple())
        remindbed.timestamp = datetime.datetime.utcnow()
        remindbed.set_footer(text=f'')
        await ctx.send(embed=remindbed)
    else:
        remindbed = discord.Embed(title=f"Reminder is set",
                                  description=f"You will get reminded at {clock}",
                                  color=discord.Color.purple())
        remindbed.timestamp = datetime.datetime.utcnow()
        remindbed.set_footer(text=f'')
        await ctx.send(embed=remindbed)
        while True:
            if clock == datetime.utcnow():
                reminded = discord.Embed(title=f"Reminded!!",
                                         description=f"{ctx.message.author.mention})",
                                         color=discord.Color.purple())
                reminded.timestamp = datetime.datetime.utcnow()
                reminded.set_footer(text=f'\u200b')

                await ctx.send(embed=reminded)

The problem is that it doesn't send the pinged msg at the given time

raven peak
#

What i need to Install to use that:

from apis.covid_api import covid_api_request
unkempt canyonBOT
#

Hey @harsh cradle!

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

slate swan
#

How would I make a highlow game in discord.py using buttons

#

I tried but the value is same every time

ripe jackal
#

Can someone help me? I'm trying to make leveling system (with the youtube power and help), but this is what I got:python @client.event async def on_message(message): with open('users.json','r',encoding='utf8') as f: user=json.load(f) try: with open('users.json','w',encoding='utf8') as f: user[str(message.author.id)]['xp']=user[str(message.author.id)]['xp']+1 lvl_start=user[str(message.author.id)]['level'] lvl_end=user[str(message.author.id)]['xp']**(1.5/4) if lvl_start <lvl_end: user[str(message.author.id)]['xp']= user[str(message.author.id)]['level']+1 lvl=user[str(message.author.id)]['level'] await message.channel.send(f"{message.author.mention} has leveled up to {lvl}!") json.dump(user,f,sort_keys=True,indent=4,ensure_ascii=False) return json.dump(user,f,sort_keys=True,indent=4,ensure_ascii=False) except: with open('users.json','w',encoding='utf8') as f: user={} user[str(message.author.id)]={} user[str(message.author.id)]['level']=0 user[str(message.author.id)]['xp']=0 json.dump(user,f,sort_keys=True,indent=4,ensure_ascii=False)
The problem is that whenever I spam message the bot starts spamming with me that I have leveled up to 0 level.
This is the error I got: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
And this is the JSON file: { "653146566881968138": { "level": 0, "xp": 1 } }
What should I do now?

manic wing
#

seems as if that isnt the json file

ripe jackal
slate swan
#
    "653146566881968138": {
        "level": 0,
        "xp": 1
    }
]```I think its this but am not sure
ripe jackal
slate swan
#
@bot.command(pass_context=True)
async def test(ctx, user: discord.Member):
    test = discord.Embed(title=f"{user.name} User's Badges", description=f"{user.public_flags.all}", color=0x2f3136)
    await ctx.channel.send(embed=test)``` how can i make this work properly? im trying to make a command that lists the users badges, and if possible, make it show the actual badge instead of the name (via custom emote)
slate swan
slate swan
#

or a place where i can find an example

dapper cobalt
#

Do you have basic knowledge of Python?

slate swan
#

mainly discord.py more than anything, but id say i do

dapper cobalt
slate swan
#

yeah

#

ik that

dapper cobalt
#

for loops, if...else statements, try...except and other usages of Python are not discord.py exclusive at all.

slate swan
#

theyre the same but different at the same time, i get what you mean

dapper cobalt
#

!resources learn Python before jumping into discord.py or your life will be a living hell while you're confused about what you're doing most of the time.

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

dawn wasp
#

Hi everyone , what do i need tp execute a code/action in a specific time like a job or task in python
Thanks in advance

crystal wind
#

Is it possible for discord bots to be able to add buttons in a message where only you can see, or the message must be visible to everyone only?

slate swan
#
@bot.command()
async def testing2(ctx):
    x = {discord.UserFlags.hypesquad_balance: 'ok'}
    flags = ctx.author.public_flags.all()
    for flag in flags:
        return x[flag]

just tested this, no output, but no error

pale zenith
slate swan
#

thats the only one

pale zenith
#

na i meant on_message not on message delete.
Send full code then

slate swan
#

uh

#

its like 2k lines lol

#

but no i dont have anything like that

cloud dawn
#

a on_message of 2k lines

slate swan
#

no

#

i mean the full code 😩

cloud dawn
#

And what is he asking for?

slate swan
#

"send full code then"......

cloud dawn
#

Of on_message

slate swan
#

OH

#

well, i dont have anything like that

#

the on_message_delete is the closest thing i have to that so

#

@pale zenith so what do you suggest

pale zenith
#

not sending

#

xD

slate swan
pale zenith
#

if you want output on discord

slate swan
waxen granite
#

Can we copy the content of a msg before it delete in a command?

#

Or event?

waxen granite
#

How?

cloud dawn
#

msg = ctx.message.content

#

best use case is ```py
msg = await ctx.send('Message', delete_after=30)
print(msg.content)

waxen granite
#

will this work in on_message_delete event?

tough wagon
unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
waxen granite
#

hm thanks

#

and i am trying to log the perms that were updated of channel for role or member, how can i do that in on_guild_channel_update?

tough wagon
unkempt canyonBOT
#

property overwrites: Dict[Union[Role, Member], PermissionOverwrite]```
Returns all of the channel’s overwrites.

This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
slate swan
#

someone help pls

sick birch
#

what is the issue?

rare star
#

So basically i'm making a command that gets all the members of a specific role and puts it into an embed. The issue is that some of these users just appear as @invalid-user. Is there a way to fix this?

reef shell
#

are you using fetch_members() for getting the members list ?

orchid talon
#

Which code should I use for auto role system

waxen granite
#
        if before.overwrites != after.overwrites:
            embed = discord.Embed(description = f"**Channel Updated:** {after.mention}", color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())
            embed.add_field(name = "Old Permissions", value=before.overwrites)
            embed.add_field(name="New Permissions", value= after.overwrites)
            embed.set_author(icon_url=before.guild.icon_url, name=before.guild)
            embed.set_footer(icon_url= before.guild.icon_url, text = f"{before.guild}")
            await logChannel.send(embed = embed)```
i tried this. sends this
#

@tough wagon

reef shell
orchid talon
waxen granite
#

on raw reaction add and remove

orchid talon
# reef shell wdym

Means I have use on member join but it is not working so which code I use insted of it

rare star
#

But I will check my code when i get home

orchid talon
reef shell
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
orchid talon
#

It is not working

reef shell
#

show code

orchid talon
#

I cant

#

I am not on my pc

reef shell
#

i guess we couldn't help you much if we don't know what's the error is

waxen granite
#

someone help me as well :3

orchid talon
#

Bro it show no error and bot is online

#

I think some problem in intents

reef shell
#

you did something wrong in the code perhaps

orchid talon
#

Let me troubleshoot it

reef shell
#

or probably you don't have this intent enabled

waxen granite
#

how do i get the guild icon url as an image?

high flame
#

the url is an image

#

how you want it to be

#

someone told me before if i requested the icon_url using aiohttp it'll return the image bytes

#

not sure but try

waxen granite
#

i want the image not this url

high flame
#

you can't.

waxen granite
#

aw

high flame
#

in the field value the you can't have an image

waxen granite
#

what about setimage

high flame
#

but you can mix both images using PIL and then send using set_image

waxen granite
#

alright

waxen granite
high flame
#

can't, i need help myself

maiden fable
#

Yea it is sending the object's str representation

marble pilot
#
import discord
from discord.ext import commands

class Announcement(commands.Cog):
    def __init__(self, Bot):
        self.Bot = Bot
    @commands.command()
    async def announce(self, ctx, is_Embed : bool,has_timestamp : bool title : str, description : str):
        #If title length is bigger than 20 characters long
        if len(title) >= 20:
            error_embed = discord.Embed(title='An error occurred while executing the command.', color=discord.Colour.orange(), timestamp=ctx.message.created_at)
            error_embed.add_field(name='Error details:',
                                  value=f'Passed "title" argument length limit. \n "title" accepts 12 characters, {len(title)} where given.')
            await ctx.send(embed=error_embed)
        else:
            #If the title or the description are in integer format.
            if type(title) == int or type(description) == int:
                error_embed = discord.Embed(title='An error occurred while executing the command.', color=discord.Colour.orange())
                error_embed.add_field(name='Please provide a string(str) type title.')

                await ctx.send(embed=error_embed)
            else:
                if is_Embed == True:
                    embed_announcement = discord.Embed(title=f"{title}", description=f"{description}")
                    await ctx.send(embed=embed_announcement)

def setup(bot):
    bot.add_cog(Announcement(bot))

I am making a announcement command but i want to make the "has_timestamp" bool argument an optional argument. How can i do that. I do not really remember the *args and **kwargs so please someone tell me how can i create optional arguments.

high flame
maiden fable
marble pilot
#

Yeah i saw the comma and wht do you mean that i cant make it optional

#

?

maiden fable
#

cz the arg is not at the end of the command

#

if u make it optional, it will say description isn't supplied

marble pilot
#

Dont remember how they work thats why i need some help

#

so you are telling me there is not a way to make it optional?

maiden fable
#

against Rules, please delete

#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

marble pilot
#

DM me if interested but please dont advertise here

#

Against rules..

celest marlin
marble pilot
celest marlin
marble pilot
#

No problem mate

#

Have a good one]

outer violet
#

How do I make it so when someone dms a bot a command that’s supposed to be in server only it responds with “this command cannot be used in dms”

maiden fable
#

But you can ask for help if u need any while coding your bot (:

marble pilot
#

^^

maiden fable
unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
marble pilot
#

and after use an exception i guess

#

for c ustom errors

outer violet
#

Would it be like an on_error?

maiden fable
#

no

#

on_command_error

#

takes in two args, ctx and error

outer violet
#

Okay thank you

marble pilot
#
    @commands.command()
    async def announce(self, ctx, title : str, description : str,**is_Embed : bool,has_timestamp : bool):

Tried that but i get the following error.

regular parameter after ** parameter
#

Any help?

outer violet
# maiden fable `on_command_error`

Is this right


client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.guild_only()):
        await ctx.send("this command cannot be used in dms")
marble pilot
#

@client.event

#

it is a decorator

marble pilot
hasty iron
marble pilot
#

hm

#

So a single * defines an arg?

outer violet
hasty iron
#

no

#

it defines a keyword argument

marble pilot
outer violet
marble pilot
marble pilot
hasty iron
#

actually i dont think you need a * at all here

marble pilot
#

I need the 2 last args to be optional

#

thats what i want

hasty iron
#

that’s not how you define an optional argument

marble pilot
#

then

hasty iron
#

you need to give if a default value

#

give it*

marble pilot
#

oh so lets say is_embed=False

#

?

hasty iron
#

in the signature yea

marble pilot
#

But at the execution of the cmd i could say like -announce blah blah True

#

to set it to true

hasty iron
#

ok

marble pilot
#

right>

#

? :>

hasty iron
#

guess

#

when does a parameter’s default gets passed in

marble pilot
#

let me try it lol

#

yea yea

outer violet
hasty iron
#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
broken igloo
high flame
#

there's many

#

i use yaml btw

broken igloo
#

Is .json config file is good?

high flame
#

yeah

broken igloo
#

Ok, thanks

dawn wasp
#

Hi everyone , what do i need tp execute a code/action in a specific time like a job or task in python
Thanks in advance

ripe jackal
#

Hello, can someone please tell me how to repair this. The on_message events make my other commands don't work. What should I do? I saw the pinned message about it, but I can't make it. This is the code: python @client.event async def on_message(msg): user=msg.author mbed=discord.Embed(title=f"{msg.author} has been warned", description="**Reason:** Bad word usage", color=discord.Color.green()) ebed=discord.Embed(title=f"**You** have been warned from _**Icy Area**_", description="**Reason:** Bad word usage", color=discord.Color.green()) for word in words: if word in msg.content: await msg.delete() await msg.channel.send(embed=mbed) await user.send(embed=ebed) await client.process_commands(msg) There is no error. What should i do?

slate swan
#

replace @quaint axle.event with @quaint axle.listen()

#

rip user

#

dc

slate swan
#

you can delete the await client.process_commands(msg) line

dawn wasp
slate swan
#

Use task loops

dawn wasp
ripe jackal
slate swan
#

does it work?

ripe jackal
#

yes

slate swan
#

nice

past ermine
#

how do i check if the bot has a permission?

#

like, there is the

if ctx.author.guild_permissions.manage_guild:
``` and i want to know, how i do that, that it checks, if the bot has the perms
slate swan
#

Use ctx.guild.me instead of ctx.author

past ermine
#

is it named manage_messages?

crystal wind
#

lp

past ermine
#

the permission to delete messages?

reef shell
#

Yes

dawn wasp
slate swan
#
  File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\marva\python\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\marva\python\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: UnboundLocalError: local variable 'channel' referenced before assignment```
#
import requests
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())
 
 
@bot.event
async def on_ready():
    print("Bot connected")
 
 
@bot.command()
async def join(ctx):

 
    data = {
        "max_age": 86400,
        "max_uses": 0,
        "target_application_id": 755600276941176913,
        "target_type": 2,
        "temporary": False,
        "validate": None
    }
    headers = {
        "Authorization": "Bot token",
        "Content-Type": "application/json"
    }
 
    if ctx.author.voice is not None:
        if ctx.author.voice.channel is not None:
            channel = ctx.author.voice.channel.id
        else:
            await ctx.send("Зайдите в канал")
    else:
        await ctx.send("Зайдите в канал")
 
    response = requests.post(f"https://discord.com/api/v9/channels/{channel}/invites", data=json.dumps(data), headers=headers)
    link = json.loads(response.content)
 
    await ctx.send(f"https://discord.com/invite/{link['code']}")
 
bot.run("token")```
#

im need help

slate swan
crystal wind
#

Is it possible for a command in python to disable a certain part of the command when aliases are being used?
For my case, I use !help [cmd], but I also added !info/!version as aliases. If I want to restricts those aliases so they don't do !version [cmd], what should I do in this case?

slate swan
#
@bot.command(pass_context=True)
async def test(ctx, user: discord.Member):
    test = discord.Embed(title=f"{user.name} User's Badges", description=f"{user.public_flags.all}", color=0x2f3136)
    await ctx.channel.send(embed=test)```
how can i fix this? i get no errors
hasty iron
#

its a method

#

you need to call it

slate swan
#

how would i call it

hasty iron
#

that’s basic python

slate swan
#

no i mean like

#

ive seen something like this before

#

with the values

hasty iron
#

ok

slate swan
#

it was something like
1 >> 1
2 >> 2
3 >> 4
4 >> 8
5 >> 16
6 >> 32...

#

is it similar to that?

hasty iron
#

no not even close

#

those are bitwise operations

slate swan