#discord-bots

1 messages Β· Page 585 of 1

maiden fable
#

Hahaha true

#

But

#

@slate swan you can do one thing

slate swan
#

.max_age maybe

maiden fable
#

Yea that only

#

Whenever u fetch an invite

#

Just store it in cache, and first check if the invite is there in the cache

#

If it ain't, then fetch it

slate swan
#

great idea

#

ty hunter !

maiden fable
#

But then, when the bot restarts, then RIP

#

?

boreal ravine
#

regex

maiden fable
boreal ravine
#

o

maiden fable
#

He wanted to get the guild information whose invite was sent

slate swan
maiden fable
#

Ah, that's cool

#

!d pickle u can use this to store the invite object tho

unkempt canyonBOT
#

Source code: Lib/pickle.py

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. β€œPickling” is the process whereby a Python object hierarchy is converted into a byte stream, and β€œunpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as β€œserialization”, β€œmarshalling,” 1 or β€œflattening”; however, to avoid confusion, the terms used here are β€œpickling” and β€œunpickling”.

slate swan
#

also , ill make the calls ( or check )only if a log channel is set for the guild which would me 10-15 at most for now

maiden fable
#

Wait, or I have an idea... Tho not a good idea, if u wanna hear...

slate swan
#

sure

#

send code , and what you except to happen and what happens instead

maiden fable
#

Make raw requests to discord (don't use the client method), and just store the JSON received in a db

boreal ravine
#

here

slate swan
#

here ofc

boreal ravine
#

people dont do dm help here afaik

maiden fable
slate swan
#

a bit harder , but better

maiden fable
#

But handle the JSON yourself

slate swan
maiden fable
#

Imho, this is a better way

#

Since u will have access to the raw JSON and u can save it anywhere then

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

whats the afkppl variable?

boreal ravine
#

mm so whats exactly wrong? the bot doesnt change your nick? you dont go afk?

#

ah

#

try using .listen() instead of .event at your on_message

slate swan
#

you cannot split a dictionary ( line 3)

boreal ravine
#

hm

#

split is only for strings

slate swan
#

!e {}.split()

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'dict' object has no attribute 'split'
slate swan
#

you probably have a error handler which is eating up the errors

#

bad bad

boreal ravine
#

!e

try():
  ...
except:
  ...
``` ~~try function~~
unkempt canyonBOT
#

@boreal ravine :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     try():
003 |        ^
004 | SyntaxError: expected ':'
slate swan
#
if isinstance( .....
   # stuff
else:
   raise error```
#

that try's except works if the bot is unable to send the command not found message

slate swan
#

its reference

#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

boreal ravine
slate swan
#

a typo i.e.

#

you had a spelling mistake

#

refrence must be reference

manic wing
#

you see

dense swallow
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

vocal plover
#

as the error states, you're inserting 6 values to 5 columns

manic wing
#

the answer is in the error

dense swallow
#

U have actually put one extra ? in values

manic wing
#

:)

dense swallow
#

Np πŸ‘

slate swan
slate swan
#

that's weird

#

So I have 3 bots, like the following:

bots\
  sir-funbot\
    main.py
  sir-modbot\
    main.py
  sir-multibot\
    main.py

Each of these bots have their own token, how would I run all these three, at the same time? Like, do I need to connect them somehow?

lament mesa
#

Maybe you can use Client.start

#

Not sure will that work though

slate swan
#

u need 3 different terminals I think

lament mesa
#

!d discord.Client.start

unkempt canyonBOT
#

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

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect").
slate swan
lament mesa
#

Wait nvm, Client.connect wont run any code after it

slate swan
#

So, is there a way?

#

To like connect all 3 bots with different tokens, and run them all?

cloud dawn
slate swan
cloud dawn
#

No

slate swan
#

then how would that work?

cloud dawn
#

!d asyncio.create_subprocess_shell

unkempt canyonBOT
#

coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Run the *cmd* shell command.

The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).

Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.

See the documentation of [`loop.subprocess_shell()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_shell "asyncio.loop.subprocess_shell") for other parameters.

Important

It is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid [shell injection](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) vulnerabilities. The [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote "shlex.quote") function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands.
cloud dawn
#

Most custom things don't have a tutorial.

slate swan
#
from discord.ext import commands
from discord import Intents
import dotenv
import os

dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")

mod_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=mod_intents)

fun_intents = Intents.all()
fun_bot = commands.Bot(command_prefix=".", intents=fun_intents)

multi_intents = Intents.all()
multi_bot = commands.Bot(command_prefix=">", intents=multi_intents)

mod_bot.run(mod_token)
fun_bot.run(fun_token)
multi_bot.run(multi_token)
slate swan
slate swan
cloud dawn
slate swan
#

Yup just notices

cloud dawn
#

So the 2 bots underneath will never see daylight.

slate swan
#

Yeah I tried and ur right

#

can anyone tell me a command for verify

#

!verify

slate swan
cloud dawn
slate swan
slate swan
cloud dawn
slate swan
slate swan
slate swan
cloud dawn
#

You can also use this

#

!d asyncio.create_subprocess_exec

unkempt canyonBOT
#

coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Create a subprocess.

The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).

Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.

See the documentation of [`loop.subprocess_exec()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_exec "asyncio.loop.subprocess_exec") for other parameters.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
cinder horizon
#

is it plausible for a bot to detect if a user got betterdiscord?

cloud dawn
#

Betterdiscord only modifies JS on the user side so not even normal users can tell if they are using it.

slate swan
# unkempt canyon

Could u at least give me a hint or an example? I don't understand the docs because of my english

slate swan
cloud dawn
slate swan
#

which one of them do I do then?

#

The second one or the first one

haughty dagger
#

any possible way to use asyncio.sleep and as well as check for button clicks in the background?

haughty dagger
#

yes

cloud dawn
#

Looks like you are describing wait_for

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
cloud dawn
#

timeout will be the time it waits

haughty dagger
#

I've already used it, but I want to use asyncio.sleep() in between command while listening to button clicks simultaneously

cloud dawn
haughty dagger
cloud dawn
slate swan
#

I haven't learned async programming yet

cloud dawn
haughty dagger
slate swan
#

Learning stuff in programming separately is bad when it's something intermediate or advanced stuff, therefor I do a project that covers these two

cloud dawn
slate swan
haughty dagger
cloud dawn
slate swan
cloud dawn
#

I'm not such a fan of the while true in a discord bot either.

haughty dagger
slate swan
#

also, why are you defining your functions inside the while True: loop?

haughty dagger
cloud dawn
# slate swan ur right mb

So try it out copy the example in a separate py file and debug something small. Then if you got it working or get into trouble you can always ask here.

haughty dagger
slate swan
cloud dawn
unkempt canyonBOT
#

coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, limit=None, **kwds)```
Create a subprocess.

The *limit* argument sets the buffer limit for [`StreamReader`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader "asyncio.StreamReader") wrappers for `Process.stdout` and `Process.stderr` (if [`subprocess.PIPE`](https://docs.python.org/3/library/subprocess.html#subprocess.PIPE "subprocess.PIPE") is passed to *stdout* and *stderr* arguments).

Return a [`Process`](https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process "asyncio.asyncio.subprocess.Process") instance.

See the documentation of [`loop.subprocess_exec()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.subprocess_exec "asyncio.loop.subprocess_exec") for other parameters.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
cloud dawn
#

I recommend looking at this (tip: read the args & kwargs)
CTRL+F is your best friend

haughty dagger
#

lemme see

#

I can see it's already deprecated

#

I'm on Py 3.9

slate swan
#

multiple bots with same file?

cloud dawn
slate swan
#

nah i mean , the X-FRST person ,
are they trying to do that or something related?

slate swan
#

oh so maybe i gussed wrong because of the subprocess_exec

cloud dawn
slate swan
#

ooh

#

I saw another method that looked way more simple in the docs

#

i see , wrong person

#
from discord.ext import commands
from discord import Intents
import asyncio
import dotenv
import os

dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")

bot_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=bot_intents)
fun_bot = commands.Bot(command_prefix=".", intents=bot_intents)
multi_bot = commands.Bot(command_prefix=">", intents=bot_intents)


@mod_bot.event
async def on_ready():
    print(f"Connected to {mod_bot.user.name}")

@fun_bot.event
async def on_ready():
    print(f"Connected to {fun_bot.user.name}")

@multi_bot.event
async def on_ready():
    print(f"Connected to {multi_bot}")


loop = asyncio.get_event_loop()
loop.create_task(mod_bot.start(mod_token))
loop.create_task(fun_bot.start(fun_token))
loop.create_task(multi_bot.start(multi_token))
loop.run_forever()
#
Connected to Sir Modbot
Connected to <discord.ext.commands.bot.Bot object at 0x000001D0FF4A2EB0>
Connected to Sir Funbot
haughty dagger
#

nvm

slate swan
#

This is the output, it seems to confuse inbetween the names?

#

What could I do?

#

wdym by confuse between the names?

#
@mod_bot.event
async def on_ready():
    print(f"Connected to {mod_bot.user.name}")

@fun_bot.event
async def on_ready():
    print(f"Connected to {fun_bot.user.name}")

@multi_bot.event
async def on_ready():
    print(f"Connected to {multi_bot.user.name}")

Returns:

Connected to Sir Funbot
Connected to Sir Multibot
Connected to Sir Modbot
#

It's wrong names

#

order of the printing statement?
doesnt depend on the order you defined the on_ready events

it gets print as per when they are ready

#

Ah I see

#

Thanks guys

#

But is there a easier way of doing this btw?

#

like, shorter

void dew
#

Can no one help me

#

Who knows is not helping and others doesn't know

cloud dawn
slate swan
#

Nvm I was wrong, it was correct

cloud dawn
slate swan
#

Right

cloud dawn
#

That's why i said to use x amount of files for x amount of bots since it can get messy fast

#

maby there is a way to make it shorter but i'd need to do research myself to find that out. Not many people do this so there will likely not be any examples.

void dew
#

Can no one help me
Who knows is not helping and others doesn't know

cloud dawn
slate swan
slate swan
#
from discord.ext import commands
from discord import Intents
import asyncio
import dotenv
import os

dotenv.load_dotenv()
mod_token = os.getenv("modtoken")
fun_token = os.getenv("funtoken")
multi_token = os.getenv("multitoken")

bot_intents = Intents.all()
mod_bot = commands.Bot(command_prefix="!", intents=bot_intents)
fun_bot = commands.Bot(command_prefix=".", intents=bot_intents)
multi_bot = commands.Bot(command_prefix=">", intents=bot_intents)


# File handler for Sir Modbot
for file in os.listdir("sir-modbot/events"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"events.{name}")

for file in os.listdir("sir-modbot/commands"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"cog.{name}")

# File handler for Sir Funbot
for file in os.listdir("sir-funbot/events"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"events.{name}")

for file in os.listdir("sir-funbot/commands"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"cog.{name}")

# File handler for Sir Multibot
for file in os.listdir("sir-multibot\events"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"events.{name}")

for file in os.listdir("sir-multibot/commands"):
    if file.endswith(".py"):
        name = file[:-3]
        mod_bot.load_extension(f"cog.{name}")

loop = asyncio.get_event_loop()
loop.create_task(mod_bot.start(mod_token))
loop.create_task(fun_bot.start(fun_token))
loop.create_task(multi_bot.start(multi_token))
loop.run_forever()
#
parent = __import__(parent_name, fromlist=['__path__'])
ModuleNotFoundError: No module named 'events'
#
bots/
  run.py (the main file for all the bots)
  sir-multibot/
    events/
      on_ready.py
    commands/
      [no files yet]

  sir-funbot/
    events/
      on_ready.py
    commands/
      [no files yet]

  sir-modbot/
    events/
      on_ready.py
    commands/
      [no files yet]
#

reason why one should not use multiple bot this way , also the error says it all

#

no module named events exist

cinder horizon
#

is there anytn like if guild.community == true:? like the bot gets to know if community is enabled

slate swan
unkempt canyonBOT
#
Fat chance.

No documentation found for the requested symbol.

maiden fable
#

Nope

#

Wym by community tho

unkempt canyonBOT
#

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.

They are currently as follows:

cloud dawn
#

beat me to it :(

slate swan
#

and check if COMMUNITY is in the list

cinder horizon
cinder horizon
slate swan
#

your wellcame

cloud dawn
#

I'm gonna play some games

#

πŸ‘‹

slate swan
#

cya panda , have fun

void dew
#

Can no one help me
Who knows is not helping and others doesn't know

slate swan
#

your problem?

slate swan
#

I don't need to?

#

Or do you mean if i initialize my event classes?

#

if so yes, i do call the __init__ method on my classes

#

Here is a example of one of the on_ready.py file:

from discord.ext.commands import Cog, Bot
import discord


class OnReady(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot

    @Cog.listener()
    async def on_ready(self):
        print(f"Started client as: {self.bot.user}")
        await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Commands: >help"))


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

#

ah wait I see you imported the modules by individual filenames

#

how do i make inventory check for the amount i have

slate swan
#

help i no brain ok

#

also replit has a built in database that you should use instead of external json files

slate swan
#

i have a stupid in my brain

slate swan
#

oh wait

#

Im an idiot I see your issue, you're prefixing these filenames with simply events. or cogs. which aren't actual relative filepaths to run.py's working directory

#

you should prefix them with sir-funbot.events or their other respective paths

#

Ohhh im an idiot too XD

#

It works now, thanks

tawdry perch
#

I saw someone importing clean_content from disocrd.ext.commands What is it?

cloud dawn
#

It converts the mentions etc to raw text

tawdry perch
#

oh

cloud dawn
#

<@tawdry perch> instead of @tawdry perch

tawdry perch
#

Oh I see

#

thx

cloud dawn
#

Can't really format it on discord

void dew
#

Can no one help me
Who knows is not helping and others doesn't know

tawdry perch
void dew
slim whale
#
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
  code = clean_code(code)

  local_variables = {
    "discord": discord,
    "commands": commands,
    "bot": bot,
    "ctx": ctx,
    "channel": ctx.channel,
    "author": ctx.author,
    "guild": ctx.guild,
    "message": ctx.message
  }

  stdout = io.StringIO()

  try:
    with contextlib.redirect_stdout(stdout):
      exec(
        f"async def func():\n{textwrap.indent(code, '       ',)}", local_variables
      )

      obj = await local_variables["func"]()
      result = f"{stdout.getvalue()}\n-- {obj}\n"
  except Exception as e:
    result = "".join(format_exception(e, e, e.__traceback__))

  pager = Pag(
    timeout=100,
    use_defaults=True,
    entries=[result[i : i + 2000] for i in range(0, len(result), 2000)]
    length = 1,
    prefix="```py\n",
    suffix="```"
  )

  await pager.start(ctx)
#

im trying to make a eval command

#

the prefix thing its prefix = '''py\n and suffix='''

tawdry perch
slate swan
#

how do i make inventory checker for how much amount i have

  for thing in users[str(ctx.author.id)]["inventory"]:
    thingy = thing["amount"]

  print(f"{thingy} found")```
cloud dawn
tawdry perch
#

breh what..?

slate swan
#

how do i make that it check how much item amount i have in my inventory

silent ermine
#

or .json or what ever

slate swan
#

can someone give me the code for a suggest command so where do u !suggest and it makes a suggestion

silent ermine
#

np

slate swan
#

ok idk where to put it

#

i need help

#

Error says all

#

what do it do?

#

Create a suggest command

#

how?

#

im new to py

#

Have you learned Python before starting your bot?

#

yea

slim whale
#

can someone help me with a eval command?

shy schooner
thick charm
#

hello

slate swan
slim whale
jade oxide
#

define it then

shy schooner
#

so

slate swan
#

how

slim whale
shy schooner
#

fix it urself

shy schooner
shy schooner
slim whale
slim whale
shy schooner
#

im gonna sleep very soon, just show me the thing

slate swan
slim whale
#

@bot.command()
async def suggest(ctx, and something more):

#

at the top of your function

jade oxide
slate swan
#

Follow the tutorial I gave you....

slim whale
#

@slate swan do u know how to make a eval command? bc i have no idea

slate swan
slim whale
#

i saw a tutorial but it doesnt work

tawdry perch
slim whale
#

Welcome back to the discord.py series! Here's a overwhelmingly requested command :D

Read description for links!

----------------------------------------Β­Β­---------------------------------------Β­-Β­--

Need Help?
Require help with your code? Why not head on over to our dedicated support discord where you can receive only the best support: https:...

β–Ά Play video
tawdry perch
#

I have few checks in my code but how do I handle them in error handlers? eg, this can raise CheckFailure bΓΉt bot can't yet handle it ```py
async def cog_check(self, ctx):
'''Allow only moderators to invoke these commands'''
user_role_ids = [role.id for role in ctx.author.roles]
return ctx.author.id == SPECIAL or any(role in user_role_ids for role in check_author())

slate swan
#
from discord.ext.commands import command, Context, Cog, Bot, has_permissions, bot_has_permissions

from discord import Embed, Colour
import random

from discord.ext.commands.core import bot_has_permissions

class Catify(Cog):
    def __init__(self, bot: Bot) -> None:
        self.bot = bot

    @has_permissions(change_nickname=True)
    @bot_has_permissions(manage_nicknames=True)
    @command(name="catify")
    async def catify(self, ctx: Context) -> None:
        responds = ["Certainly not.", "Not likely.", "Nah."]
        cats = ["α“•α˜α—’", "α˜‘α˜α—’", "α•¦α˜α—’", "α“‡α˜α—’", "α˜£α˜α—’"]
        catify = random.choice(cats)
        if len(str(ctx.author.name)) == 23 or len(str(ctx.author.nick)) == 23:
            respond = random.choice(responds)
            embed = Embed(
                title=f"{respond}",
                description="Your display name is too long to be catified! Please change it to under 26 characters.",
                color=Colour.brand_red()
            )
            await ctx.send(embed=embed)
        else:
            await ctx.author.edit(nick=f"{ctx.author.name} | {catify}")
            await ctx.send(f"Your catified nickname is: `{ctx.author.nick}`")


def setup(bot: Bot) -> None:
    bot.add_cog(Catify(bot))

Error:

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

What am I doing wrong?

silent ermine
#

!cod

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

silent ermine
#

put the code and error in it

#
@client.command(pass_context = True)
async def mute(ctx, member: discord.Member):
     if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
        role = discord.utils.get(member.server.roles, name='Muted')
        await client.add_roles(member, role)
        embed=discord.Embed(title="User Muted!", description="{0} was muted by {1}!".format(member, ctx.message.author), color=0xff00f6)
        await client.say(embed=embed)
     else:
        embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
        await client.say(embed=embed)```
#

erm so server permissions

#

@client.has_permissions(administrator=True) next to the

slate swan
#

anyone know how to send a message to a user using their user id?

#

specifically here

#

what?

void dew
#

I don't know that

slate swan
#

Getting the guild id in an on_user_update event in discord.py does anyone know how to do this??

slate swan
#

i mean dm as in direct chat messages

vocal magnet
slate swan
#

Error ?

#

You cannot add parameters as you wish

#

Remove the *, message parameters

#

does not work either

stone palm
#

how do i edit the most recent message in a channel
the most recent message from the bot

slate swan
slate swan
#

like this?

#

No

#

do i have to use send?

#

Yes

#

or send message

#

oh

#

|send_message` is old code

#

You shouldn't copy paste from internet old code

#

And it's get_user

#

And the IDs are integers, not strings

#

true

#

thank you

#

And it's not bot.send but just user.send

#

thanks again

#

And?

#

That's what your code does, it's correct

#

Add .mention if you want to mention the user

slate swan
#

i think i did something wrong here

#

i did not get any error but when i type shoot nothing happened

#

Then just ctx.message....

stone palm
#

how do i edit the most recent message in a channel
the most recent message from the bot

slate swan
#

Remove the message argument, already told you

#

do i have to use prefix while using in server?

slate swan
#

It only takes specific arguments which are only ctx and error

slate swan
#

And no you don't, it checks for every message, as the event name says

#

ah okay

#

message.content, basic python objects...

#

still 😦

#

it doesnt send me a dm

#

why doesnt it work

#

where

#

No

#

Don't mislead people

#

😐

slate swan
# slate swan

The user is not in cache, so you'd need to use ...get_user(id) or await bot.fetch_user(id)

#

It's not a command, read the code please....

#

And I'm not your bro

#

oh god

slate swan
#

Anyways, enjoy getting mislead, have a great day 2DRenownThumbsUp

slate swan
slate swan
#

any idea why?

#

Again, remove the unneeded user,

#

Just user.send("blah")

covert igloo
slate swan
#

Do you even get errors

#

no it just did not send me any dm

#

oh wait i have an idea i'll use a print()

#

!code ;-;

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

Dude lmao

#

You can't add any arguments to events

#

debugging

#

When will you get that

tawdry perch
#

I have few checks in my code but how do I handle them in error handlers? eg, this can raise CheckFailure bΓΉt bot can't yet handle it ```py
async def cog_check(self, ctx):
'''Allow only moderators to invoke these commands'''
user_role_ids = [role.id for role in ctx.author.roles]
return ctx.author.id == SPECIAL or any(role in user_role_ids for role in check_author())

slate swan
#

An on_message event only takes a message argument

#

So stop misleading people

#

okay so IF block is not triggered

#

I already told you that a few minutes ago....

#

this does not print the print statement

#

so if block is FALSE?

#

What message do you send

#

shoot

#

right?

#

Wait, why do you use await get_user

#

await is only for fetch_user

#
bot.get_user(id)
await bot.fetch_user(id)

Like that

#

Only fetch_user is a coroutine

#

oo

#

get user doesnt have to be coroutine

#

you are right

#

No, get_user is not a coroutine, nothing to do with having to be one or not

#

right

slate swan
#

if loop evaluates to false

#

What is your code now

#

Print the message content

#

message.content ?

#

Yes

#

in the IF loop or out

#

Before your if statement of course

#

ok

#

all how write code in frem ?

slate swan
#

🀨

#

not even this

#

other commands work tho

#

Do you have another on_message event?

#

no

#

only one

#

!!!!????????

slate swan
slim whale
#
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
  async def GetMessage(
    bot, ctx, contentOne="Default Message", contentTwo="\uFEFF", timeout=100
  ):
    embed = discord.Embed(title=f"{contentOne}", description=f"{contentTwo}",)
    sent = await ctx.send(embed=embed)
    try:
        msg = await bot.wait_for(
            "message",
            timeout=timeout,
            check=lambda message: message.author == ctx.author
            and message.channel == ctx.channel,
        )
        if msg:
            return msg.content
    except asyncio.TimeoutError:
        return False


  def clean_code(content):
    if content.startswith("```") and content.endswith("```"):
        return "\n".join(content.split("\n")[1:])[:-3]
    else:
        return content

  code = clean_code(code)

  local_variables = {
    "discord": discord,
    "commands": commands,
    "bot": bot,
    "ctx": ctx,
    "channel": ctx.channel,
    "author": ctx.author,
    "guild": ctx.guild,
    "message": ctx.message
  }

  stdout = io.StringIO()

  try:
    with contextlib.redirect_stdout(stdout):
      exec(
        f"async def func():\n{textwrap.indent(code, '       ',)}", local_variables
      )

      obj = await local_variables["func"]()
      result = f"{stdout.getvalue()}\n-- {obj}\n"
  except Exception as e:
    result = "".join(format_exception(e, e, e.__traceback__))``` my eval command doesnt says anything
slate swan
slim whale
slate swan
edgy meadow
#

Hi, how can i run a exit function inside a class and use commands for discord in it?

placid escarp
#

how can i get nsfw gifs for d.py??

tawdry perch
placid escarp
tawdry perch
#

I don't think this is best place to ask in, I can be wrong as well

slate swan
#

There're a few out there

dapper cobalt
#

Ah, no it's not.

valid niche
placid escarp
slim whale
#
@bot.command()
async def move(ctx, user : discord.Member, channel:int):
  await user.move_to(channel)
  await ctx.send(f"He movido a {user.mention} al canal de voz {channel.mention}!")```
#

why does this not work?

#
  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 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
slate swan
#

Type hint your channel argument to discord.VoiceChannel instead of an int

blazing coral
#
async def strike(ctx, member: discord.Member, *, reason):

    current_strike_count = len(
        await client.strike.find_many_by_custom(

        {
            {user_id: member.id, guild.id: member.guild.id}
        }
        )
    ) + 1
    strike_filter = {user_id: member.id, guild.id: member.guild.id, number: current_strike_count}
    strike_data = {"reason": reason, "timestamp": ctx.message.created_at, "striked by": ctx.author.id}

    await client.strike.upset_custom(strike_filter, strike_data)

    await ctx.send(f" you have been striked {reason}, {current_strike_count} ")````
#

it give me an error and i dont know what it wants

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

Traceback (most recent call last):
  File "C:\Users\ggmin\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\ggmin\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\ggmin\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: AttributeError: 'Bot' object has no attribute 'strike' ````
#

thats the error

#

its not all my code

#

trying to learn how to do somthing like this so used somone elses code to base off of to make mine

#

its how i have been learning

slate swan
#

Is it possible to edit this icon on the playing status?

slate swan
pliant gulch
#

Message content was not removed

#

Lol what?

weary gale
#

anybody have an announce command code i can use pls

#

that i can !announce 'message'

#

or something like that

slate swan
#

We don't give code, we help you progress with the issues you face

pale zenith
valid niche
#

you cannot do stuff = await func()['key']

#

it will first run the ['key'] and then the await

pliant gulch
#

You need to surround await get_entry with round brackets before indexing

#

(await ...())[i]

valid niche
#

if you want it the other way around, first do the await func, get the result, and subscript that

#

or surround it with round brackets

pliant gulch
#

Just like in math, basically your forcing the order of operations

slate swan
#

Hello, how can we make our bot create a role or what they have the role can see it?

pale zenith
#

?

slate swan
#

Is it possible to change this icon

pale zenith
#

Bots cant use rich presences, last i checked.

mortal dove
#

Can I have some easyish bot command ideas?

pliant gulch
slate swan
#

my user info command shows account creation date and user badges, im trying to make it find badges for users outside of shared guilds, i understand that i have to use fetch with this, but id have to also use a memberconverter to do so, which i dont know how to do, so ive thought of alternatives, could i do something like (user: Union[discord.User, discord.Member, id:int)]

pliant gulch
#

A member is connected to a guild, it wouldn't be possible if you don't have a shared guild

slate swan
#

thats just what i was told lol

slate swan
#

so if the user id that the author sent in the userinfo command belongs to a user not in the guild, then it doesnt return the rest of the command like status, presence, and joined time (which is what i also have in the command)

#

just badges and creation time (which i have defined)

pliant gulch
#

You just typehint Member | User like you are doing right now

#

Then you isinstance the user variable

#

To check whether or not its a User or Member

slate swan
pliant gulch
#

Why do you have the id??

slate swan
pliant gulch
#

You can just typehint User

#

There is no point of id here

#

And that isn't even valid

slate swan
#

whats typehint..

pliant gulch
#

Union[...] is a typehint,

slate swan
#

ohh

pliant gulch
#

You are typehinting User | Member currently

slate swan
#

alright

#

so to clarify, ...(user: Union[discord.User, discord.Member]): can work for what i need it to do?

pliant gulch
#

Yes, then you isinstance user to check if its a User or Member

#

If it is a user you pass the id attr of user to fetch_user

slate swan
#

alright, that doesnt seem all that difficult

slate swan
pliant gulch
#

fetch_user returns a discord.User object, this object has an id attribute

#

You can access it via dotnotation or getattr

unkempt canyonBOT
slate swan
#

ty

faint echo
#

stop sending the file and embed together

#

only send one, in this case the embed.

#

that should work

#

Oh ok

#

Yep your fix is the only fix

#

what I said up above does not work

#

just tried

jade tartan
#

How?

boreal ravine
#

Read. The. Error.

valid niche
#

also

    for role in guild.roles:
        if role.name == "Muted":
            await member.add_roles(role)
``` is an extremely inefficient way to achieve this, you should either do guild.get_role(id), or if you insist on using the name, use `discord.utils.get(guild.roles, name='Muted')`
jade tartan
valid niche
jade tartan
pliant gulch
#

I mean, all get methods in dpy are O(n) iirc so

#

Yea it should be

valid niche
#

so even if only for that last part it's better

unkempt canyonBOT
#

discord/utils.py lines 436 to 449

if len(attrs) == 1:
    k, v = attrs.popitem()
    pred = attrget(k.replace('__', '.'))
    for elem in iterable:
        if pred(elem) == v:
            return elem
    return None

converted = [(attrget(attr.replace('__', '.')), value) for attr, value in attrs.items()]

for elem in iterable:
    if _all(pred(elem) == value for pred, value in converted):
        return elem
return None```
pliant gulch
#

By far def not efficiently made

jade tartan
#

How do i make it remove the role?

valid niche
jade tartan
pliant gulch
robust ridge
#

my code wont work

blazing coral
#

how do i mention a specific channel and a specific role

robust ridge
#

ive done everything

valid niche
blazing coral
#

i did that

valid niche
#

or channel.mention/role.mention will generate these for you

blazing coral
#

give me an error

valid niche
robust ridge
#
import discord
from discord.ext import commands
import discord
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, MissingPermissions
from discord.utils import get
import os
import datetime
import asyncio
import time

intents = discord.Intents.all()
intents.members = True
client = commands.Bot(command_prefix = "$", intents=intents)

@client.event
async def on_ready():
  print("We have logged in as {0.user}".format(client))

#response messages
@client.event
async def on_message(message):
    if message.content == "ok":
      await message.channel.send("ok is gay")
    if message.content.startswith("lol"):
      await message.channel.send("Hi nub")

@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    await ctx.message.delete()
    await member.kick(reason=reason)

@kick.error
async def kick_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send("You don't have permission to kick people")

@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
  await member.ban(reason=reason)

my_secret = os.environ['TOKEN']
client.run(my_secret)
valid niche
robust ridge
#

kick wont work

#

like when i do the kick command nothing happens

#

like nothing

valid niche
#
  1. Why do you have client = commands.Bot? That's just bad naming convention
  2. It's the on_message
pliant gulch
#

Your overwriting the default on_message event, which is where the bot internally does process_commands

#

Either change your on_message to a listener via .listen() instead of .event

pliant gulch
#

Or manually add process_commands

#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
valid niche
#

and also please use proper naming for your bot instance

#

!pep 8

unkempt canyonBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

robust ridge
#

so how do i add the process commands

#

i mean where

#

nvm

blazing coral
#
async def shopclose(ctx):
    embed = discord.Embed(
        title=' Shop Status ',
        description=f' Keep and eye on {channel.mention_866571652518641684} for the reopening . ',
        colour=discord.Colour.red())

    embed.add_field(name=f" {role.mention_866837934611234838} :",
                    value=" WARZ shop is closed  ",
                    inline=True)
    embed.set_image(url='https://www.bing.com/images/search?view=detailV2&ccid=D4b7Nqnb&id=EC0104FDB53D8D309F68E2144FBCC1B208B68AF9&thid=OIP.D4b7NqnbO0MtNZHjAAb_ngHaEK&mediaurl=https%3a%2f%2fth.bing.com%2fth%2fid%2fR.0f86fb36a9db3b432d3591e30006ff9e%3frik%3d%252bYq2CLLBvE8U4g%26riu%3dhttp%253a%252f%252fmarketingland.com%252fwp-content%252fml-loads%252f2015%252f03%252fwere-closed-sign-ss-1920.jpg%26ehk%3d%252bzG3XCKcq0Tziqc7a3lKRQSq9I7avPDVigdXMI2wTEQ%253d%26risl%3d%26pid%3dImgRaw%26r%3d0&exph=1080&expw=1920&q=closed++sign&simid=608027194431859752&FORM=IRPRST&ck=3F58E2BEAD445516EFCA189E39308CE6&selectedIndex=8')
    await ctx.send(embed=embed)```
#

the error


Traceback (most recent call last):
  File "C:\Users\ggmin\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\ggmin\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\ggmin\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: NameError: name 'channel' is not defined```
boreal ravine
#

channel isnt defined

valid niche
#

channel doesn't exist, and even if it did, mention_866571652518641684 is not an attribute of a channel

blazing coral
#

i get that but when i put it in like

async def shopclose(ctx, channel.mention, role.mention)

boreal ravine
#

Bruh

blazing coral
#

i just seen his mssage

valid niche
blazing coral
#

ok

valid niche
#

you must supply a descriptive name, and a . character is NOT permitted

blazing coral
#

ok

boreal ravine
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
valid niche
#

just do <#id> at that point

boreal ravine
valid niche
boreal ravine
#

πŸ™ƒ

blazing coral
pliant gulch
#

Imo API calls should be avoided when they aren't needed for an action, they shouldn't be avoided to the point where it becomes cumbersome to do what you want effectively

valid niche
boreal ravine
valid niche
pliant gulch
#

That sounds a lot better

boreal ravine
#

[#python-discussion](/guild/267624335836053506/channel/267624335836053506/) like this

blazing coral
#

yeah what i ment sorry

#

so now what about the role

valid niche
#

#python-discussion == [#python-discussion](/guild/267624335836053506/channel/267624335836053506/)

blazing coral
#

alright

boreal ravine
#

<@&764802720779337729> = <@&764802720779337729>

valid niche
#

<@!user_id> or <@user_id> (discord really is inconsistent when it comes to user mentions. It accepts both as input, and returns either with or without !)
<@&role_id>
<#channel_id> (can be any channel type)

pliant gulch
#

You can also mention voice channels

boreal ravine
#

Channel

pliant gulch
#

Cause some people don't know you can

#

<@!user_id> or <@user_id> (discord really is inconsistent when it comes to user mentions. It accepts both as input, and returns either with or without !)
This used to be here for nicknames iirc

#

But now there is no difference

valid niche
#

it's the same yes, but discord returns either one or the other and it's just thinkmon

#

like just remove the one without ! to make it consistent a special character for each case

pliant gulch
#

They used to use it for nicknames Β―_(ツ)_/Β―

#

Then it got deprecated

valid niche
#

but not anymore so yeah

#

just remove it at that point

pliant gulch
#

Not a big deal to remove it or not

#

Seems just like a nitpick

blazing coral
#

alright the channel one worked but the role one didnt

boreal ravine
#

How didn't it work

valid niche
#

the thing that bothers me is that if you want to make something that can find mentions in a message, you need to check both cases because discord just doesn't return one or the other, but a mixmash

boreal ravine
#

🀨

pliant gulch
valid niche
#

it's been deprecated for quite a while, and it's not just visual but actually a logical thing programmers have to keep in mind

slate swan
#

why does this not work?

valid niche
pliant gulch
#

This isn't a normal usercase

slate swan
#

if looop evaluates to false

valid niche
pliant gulch
slate swan
#

when i type shoot in server nothing happens

pliant gulch
valid niche
pliant gulch
#

What stage are you guys at right now

valid niche
#

tho a lot of devs are currently very busy with school so it's been a bit slower the last few weeks

valid niche
# pliant gulch What stage are you guys at right now

currently being very busy with getting everything working again because someone decided to push a major update without testing it properly and it's riddled with errors, but it's also a lot of valuable code and not worth it to just revert

pliant gulch
#

Why do non maintainers have power to push directly?

valid niche
valid niche
pliant gulch
#

Ah....

valid niche
#

it was literally the owner of the library

pliant gulch
#

Yikes

blazing coral
pliant gulch
#

Me and blanket are grinding lefi down right now pushing hella commits, thats why I added a lot of CI

#

So I don't break anything

#

Blanket alr finished voice impl, and now I just need to finish interactions and its off to v1.0.0

blazing coral
#

It mentions the channel just not the role

valid niche
blazing coral
#

But it did thou like I said it mentions the channel not the role in the embed

boreal ravine
pliant gulch
valid niche
blazing coral
#

Oh alright

boreal ravine
blazing coral
#

Makes sense

valid niche
pliant gulch
#

Mods thought it was him

boreal ravine
#

ah thats what he told me

valid niche
#

i mean i could push to pypi right now, but once you import the library you get an error right away haha

pliant gulch
#

Your codebase owner should really learn how to do packages correctly

#

At least repo's getting serious development

valid niche
#

i've tried to tell him a lot, just he pushed without thinking since he did a ton of work

#

he sometimes just is a bit overambitious and just spurs out random things that aren't exactly...right

pliant gulch
#

A tip from me is to add a lot of CI

#

Catches a lot of things

#

Like if you take a look at lefi's repo, you can see a lot of CI and tests

#

I even went a bit overboard and wrote shell scripts and a Makefile

valid niche
#

i have no idea what a CI even is and i doubt anyone else knows apart from maybe alec

pliant gulch
#

Workflow stuff, continuous integration

valid niche
#

if i have some time i might just see if i can take a look

pliant gulch
#

And you should start documenting all your models in disthon, it gets really hard to catchup later on

#

I would know

#

πŸ˜“

valid niche
#

we are aware and it's on the agenda

#

we'll try to add at least docstrings to everything in the near future

pliant gulch
#

Are you gonna be doing RST docs

valid niche
pliant gulch
#

I'm talking about your docstrings format

blazing coral
#

so how would i go about getting my command message to delete after the embed is sent

valid niche
valid niche
#

!pep 287

unkempt canyonBOT
#
**PEP 287 - reStructuredText Docstring Format**
Status

Active

Created

25-Mar-2002

Type

Informational

pliant gulch
#

Ah RST, gl

blazing coral
pliant gulch
#

Does disthon have a support server or a group dm, cause I have time to do code reviews, seems like you guys need it

blazing coral
#

i want the command to delete after the embed has been sent

pliant gulch
#

A fellow wrapper maintainer gotta communicate with others

pliant gulch
pliant gulch
valid niche
#

wait let me add it to the readme file

#

there we go it's in the readme now

blazing coral
#

sorry to be a bother by the way

valid niche
#

ctx.message.delete()

blazing coral
#

so it would be somthing like

valid niche
#

also next time, just put the message, no need to reply to a random message

blazing coral
#
await ctx.message.delete(pp!d shopopen)```
#

@valid niche

#

like that

valid niche
#

there's no argument

#

it's just....delete

blazing coral
#

? im lost what you mean by just delete

boreal ravine
#

it takes no arguments he means

blazing coral
#

oh alright

unkempt canyonBOT
#

discord/message.py lines 1109 to 1116

async def delete(self, *, delay: Optional[float] = None) -> None:
    """|coro|

    Deletes the message.

    Your own messages could be deleted without any proper permissions. However to
    delete other people's messages, you need the :attr:`​~Permissions.manage_messages`​
    permission.```
boreal ravine
#

smile

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
boreal ravine
#

yes

slate swan
#

hey can someone please help me with this

#

when i type shoot in server nothing happens

boreal ravine
#

Is there an error

slate swan
#

no

#

there is no error

blazing coral
#
async def shopclose(ctx, delete):
    await delete('pp!d shopclose', delay=None)

    embed = discord.Embed(
        title=' Shop Status ',
        description=f' Keep and eye on #audit-log for the reopening . ',
        colour=discord.Colour.red())

    embed.add_field(name=f"  :",
                    value=" WARZ shop is closed <@&907084137490448435>  ",
                    inline=True)

    await ctx.send(embed=embed)```
#

there is the code

#

it didnt work

#

here is the error

boreal ravine
#

Don't ping random people

#

So whats the error

blazing coral
#
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: delete is a required argument that is missing.```
boreal ravine
#

ah

blazing coral
#

i dont know why cause i have it

#

there

boreal ravine
#

delete doesnt take any arguments only keyword arguments

slate swan
valid niche
boreal ravine
blazing coral
#

alright

boreal ravine
#

delete is gonna be undefined so use this

#

!d discord.ext.commands.Context.message

unkempt canyonBOT
blazing coral
#

but if i remove the string im going to get a syntax error

boreal ravine
#

you aren't?

blazing coral
#

but i did

boreal ravine
#

Whats the error

blazing coral
#
    await delete(pp!d shopclose)
                   ^
SyntaxError: invalid syntax```
boreal ravine
#

Do you know what a string is

blazing coral
#

' '

#

i belive thats it

boreal ravine
#

those are quotation marks

blazing coral
#

i know what an f string is

boreal ravine
#

"string" <= this is a string

boreal ravine
blazing coral
#

yes so a " " is a string

boreal ravine
#

your supposed to delete the string not remove the quotation marks from it

blazing coral
#

ok

#

its still saying delete is a required argument that is missing thou

boreal ravine
#

you arent supposed to have a delete argument

#

we never said that

boreal ravine
slate swan
#
# Server is mc.hypixel.net
async with aiohttp.ClientSession() as session:
    async with session.get(str('https://api.mcsrvstat.us/2/') + str(server)) as OpenURL:
        theJSON = await OpenURL.json(content_type=None)

Keep getting Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0) error, don't know why

#

so i figured out this whole block is not running

#

any idea why?

#

ok

#

bot.listen()

#

@bot.event

#

what?

slate swan
#

i am using bot.listen so it doesn't over ride bot.command

slate swan
boreal ravine
slate swan
boreal ravine
#

ah

#

that isnt the full URL then?

#

i mean this =>https://api.mcsrvstat.us/2/

slate swan
#

str('https://api.mcsrvstat.us/2/') + str(server)

#

o

#

ohhhh

#

the slash is canceling the '

#

nvm

#

I don't need help anymore lmaocry

#

nvm, didn't fix lol lmaocry

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").

Example...
slate swan
#

check the example

mortal dove
#

When I using on_member_join/remove, how do I tell what guild they left?

slate swan
#
@commands.Cog.listener()
async def on_guild_remove(self, guild):
    print(guild.name)
mortal dove
#

Ah yeah, that makes sense. Thanks anyways haha

slate swan
#

lol

#

(me just realizing that I sent the wrong thing)

mortal dove
#

nah you sent the right thing

#

well I mean it works

#

Wait how would I get the member then?

slate swan
#

I sent on_guild_remove, not on_member_leave

vapid berry
#

#bot-commands

mortal dove
slate swan
#

ok

boreal ravine
robust ridge
#

need help mentioning someones tag when i ban them

#

idk what it is

#

if its like user.tag

slate swan
#

user.discriminator

boreal ravine
#

!d discord.Member this returns the member name/tag iirc

robust ridge
#

or member.tag

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

ok ty

slate swan
#

what should i use then?

boreal ravine
#

.listen() is already great why would you change it

slate swan
#

so what do u recommend?

#

what's causing the problem

#

you tell him then lmaocry I have no experience with .listen() which is why I wouldn't use it.

#

why does it not get triggered

boreal ravine
#

you should understand things first before commenting on stuff

robust ridge
robust ridge
slate swan
#

what u mean?

#

other commands still work

slate swan
boreal ravine
slate swan
#

no

#

thats what im asking

#

nothing

robust ridge
#

embed.add_field(name = "test", value = discord.Member, inline = True)

boreal ravine
sick birch
boreal ravine
#

🀨

robust ridge
#

oh

slate swan
slate swan
sick birch
#

the way it's often done: .event with on_message to check if the message is by a bot, if it is, return ,if not process_commands

slate swan
sick birch
#

i've seen it be done in danny's bot that way

slate swan
sick birch
#

what do you mean by "not work"

boreal ravine
sick birch
#

and can you send your code?

slate swan
#

it just doesnt work, neither it prints the print() command nor it does anything when i type shoot

sick birch
#

okay, can we see the code ?

robust ridge
#

whats the object again lol

slate swan
slate swan
boreal ravine
#

maybe the event isnt getting triggered

slate swan
#

u want the full code?

sick birch
#

no just the .listen

slate swan
#

exactly!

sick birch
#

the print isn't getting triggered?

slate swan
#

right

#

its not getting triggered

sick birch
#

is this bot verified? are the message intents on?

slate swan
sick birch
#

is your bot verified?

slate swan
#

do u mean this?

slate swan
sick birch
#

enable message intents

slate swan
#

where?

robust ridge
#

check developer portal

#

for ur intents

sick birch
#

in the dev portal, also in the code

robust ridge
#

hmm

sick birch
#

intents.messages = true

mild token
slate swan
sick birch
#

what about in the code?

robust ridge
#

an example with code

boreal ravine
#

!d discord.Intents.messages

unkempt canyonBOT
slate swan
#

u mean this right?

#

how do i enable it in code?

sick birch
slate swan
#

intents.messages = true

sick birch
jade tartan
#
roles = discord.utils.get(member.guild.roles,"Member", "β–¬β–¬β–¬ Reaction Roles β–¬β–¬β–¬", "β–¬β–¬β–¬ Member Roles β–¬β–¬β–¬")
#

Is that how you add multiple roles when a member joins?

#

or is it autorole

sick birch
#

no

mild token
#
# a class
 
 

class Dog: 

     

    # A simple class

    # attribute

    attr1 = "mammal"

    attr2 = "dog"
 

    # A sample method  

    def fun(self): 

        print("I'm a", self.attr1)

        print("I'm a", self.attr2)
 
# Object instantiation

Rodger = Dog()
 
# Accessing class attributes
# and method through objects

print(Rodger.attr1)
Rodger.fun()
sick birch
#

utils.get takes an iterable, and an attribute

robust ridge
#

OH

#

I GET IT NOW T Y

jade tartan
mild token
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

boreal ravine
#

!d discord.Guild.get_role

unkempt canyonBOT
boreal ravine
#

^

jade tartan
#

k thnx

#

But i dont want the role id

slate swan
jade tartan
#

i need the name of it

#

?

sick birch
boreal ravine
#

^

sick birch
#

or use a map()

boreal ravine
#
a = discord.utils.get()
b = discord.utils.get()
``` and so on
slate swan
#

it still doesnt work

sick birch
#

map/list comp works just as well

slate swan
#

😭

sick birch
sick birch
mild token
#

It will return the first match

sick birch
slate swan
#

alright

jade tartan
#

right?

mild token
jade tartan
#

if that make sense

mild token
#

If u check documentation it has mentioned where to use await

jade tartan
#
async def on_member_join(member):
        guild = client.get_guild(730651046459998218)
        channel = guild.get_channel(885464532959526913)
        myEmbed = discord.Embed(title = f"Welcome",
        description= f"You are member {guild.member_count}, \n Enjoy your stay here and dont forget to read the await [#904279966693355550](/guild/267624335836053506/channel/904279966693355550/)", color=0x0ff00)
        myEmbed.set_image(url=f"{member.avatar_url}")
        await channel.send(embed=myEmbed)
        autorole = discord.utils.get(member.guild.roles, name='Unverified')
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        roles =  discord.utils.get(ctx.guild.roles,name= "your role name")
        await member.add_roles(autorole)

Here is my code

slate swan
#

i cant use the command still

#

any idea why?

mild token
#

Wait aren't u storing in variable?

slate swan
mild token
#

discord.utils.get line will find and return obj

slate swan
mild token
#

U need to store it in order to work with it

supple thorn
mild token
slate swan
#

so what should i do

supple thorn
mild token
#

Ahh

slate swan
mild token
#

Got it

jade tartan
supple thorn
mild token
#

Then only u can assign

slate swan
mild token
#

@slate swan make if both in same vertical line

slate swan
#

meaning

#

?

jade tartan
mild token
#

Check your 2nd if ,it has more space

mild token
jade tartan
#

ohh ik this is where i would write the variable like this

slate swan
#

you want me to backspace?

boreal ravine
unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

jade tartan
#

roles = discord.utils.get(ctx.guild.roles,name= "Levels")

mild token
#

Yes 2nd if has more space

slate swan
mild token
slate swan
#

so this would work?

mild token
#

Check 2nd if mate

slate swan
mild token
#

Make it same as 1st if

slate swan
jade tartan
mild token
#

2nd if has more space at starting

jade tartan
#

i mean colum

#

n

slate swan
gaunt herald
#

Can someone tell me how to make music botthinkmon

boreal ravine
mild token
#

In python indentation is important in your case after return everything is ignored

slate swan
gaunt herald
boreal ravine
slate swan
slate swan
gaunt herald
#

Ok

slate swan
#

why does this not work? i did not get any error but bot doesn't reply in server

slate swan