#discord-bots

1 messages · Page 590 of 1

coarse shore
#

Mongo db or mysql

ornate lichen
#

what about 9.9%

coarse shore
#

There is a free plan in mongo db its called atlas

river kindle
#

i don't know how to use db

coarse shore
river kindle
#

uhmmm okok

boreal ravine
coarse shore
river kindle
#

why?

boreal ravine
#

🤨

slate swan
#
        acts = member.activities
        act = [i for i in acts if isinstance(i, discord.CustomActivity)]
        if act:
            act = act[0]


        if discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities) == True:
            listening = "Listening to Spotify ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"
            act = ""
        elif discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities) == False:
            listening = ""

        if discord.utils.find(lambda act: isinstance(act, discord.Game), member.activities) == True:
            playing = "Playing A Game ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"
            act = ""
        elif discord.utils.find(lambda act: isinstance(act, discord.Game), member.activities) == False:
            playing = ""
            act = ""

        if discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities) == True:
            streaming = "Streaming on Twitch ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"
            act = ""
        elif discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities) == False:
            streaming = ""

        else:
            act = 'None'

        await ctx.send('{playing}{listening}{watching}{act}')```
`Command raised an exception: UnboundLocalError: local variable 'playing' referenced before assignment`
thats basically the part im having struggles with, but im not sure why that error comes up 
i defined 'playing'
coarse shore
vernal osprey
#

how would i start a timer without using asyncio.sleep like it should'nt sleep. the bot shud be online

boreal ravine
slate swan
#

so indents are whats causing the problem right

boreal ravine
#

maybe

slate swan
#

so i dont see how indents would be the problem

boreal ravine
#

I said maybe

boreal ravine
slate swan
#

any ideas of what else it may be

boreal ravine
#

yes, the error

#

!global

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

boreal ravine
#

🙂

slate swan
#

never really used def tbh

#

hmm

boreal ravine
slate swan
#

ok well

boreal ravine
#

🤨

slate swan
#

ive used it

boreal ravine
#

your literally using it to make commands

slate swan
#

but not in command statements

boreal ravine
#

you are

slate swan
#

obviously async def

boreal ravine
#
def hello(ctx):
    ...
``` 🤨
slate swan
#

^^

coarse shore
#

L

boreal ravine
slate swan
#

but how am i meant to use that in a variable for a command output

#

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 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: 'Context' object has no attribute 'owner'

slate swan
ornate lichen
#

client.run(os.getenv("BOTTOKEN"))

#

whats wrong with this

coarse shore
#

Insert bot token in env tab with same variable name

boreal ravine
ornate lichen
#

i did

ornate lichen
boreal ravine
unkempt canyonBOT
#

property owner: Optional[discord.member.Member]```
The member that owns the guild.
coarse shore
boreal ravine
#
global playing
...
ornate lichen
coarse shore
#

It should be put into env tab in railway repo settings

ornate lichen
#

so i dont put in my vs code?

boreal ravine
#

No. You don't.

coarse shore
ornate lichen
#

yeah im doing that

ornate lichen
# coarse shore Github and lauch from github

line 1: cannot unmarshal !!str web:pyt... into map[string]string
ERROR: failed to build: exit status 3
ERROR: failed to build: executing lifecycle: failed with status code: 51

#

this is my procfile web:python main.py

#

is it wrong?

boreal ravine
#

Tias

#

where the error came from

ornate lichen
#

@coarse shore is the railway thing unlimited usage?

slate swan
#

ok im back

ornate lichen
#

for free

ornate lichen
#

ok

slate swan
#
        acts = member.activities
        act = [i for i in acts if isinstance(i, discord.CustomActivity)]
        if act:
            act = act[0]


        playing = ""
        listening = ""
        streaming = ""
        act = 'None'

        if discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities):
            act = "Listening to Spotify ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"

        elif discord.utils.find(lambda act: isinstance(act, discord.Game), member.activities):
            act = "Playing A Game ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"


        elif discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities):
            act = "Streaming on Twitch ![rich_presence](https://cdn.discordapp.com/emojis/907387984226173008.webp?size=128 "rich_presence")"```
no errors, no handlers, no exceptions, but the output remains 'None'
#

sry for flood <3

boreal ravine
#

Hm

mental kraken
#

Required python 3.8 or higher

slate swan
#

oh, the status value is {act} btw

boreal ravine
#

Change ctx.author.guild_id to what I said earlier

boreal ravine
tame marsh
ornate lichen
#

ERROR: failed to launch: determine start command: when there is no default process a command is required
ERROR: failed to launch: determine start command: when there is no default process a command is required
ERROR: failed to launch: determine start command: when there is no default process a command is required
ERROR: failed to launch: determine start command: when there is no default process a command is required

ornate lichen
#

for the bot?

#

Your apps root didn't return a 200

boreal ravine
#

mine?

#

wot

ornate lichen
#

thats th error

#

warning

ornate lichen
boreal ravine
#

yes

#

I mean

#

try googling how to use it

ornate lichen
#

okayy

main forum
#

Is there a way to edit the messages content and embed like: edit(content=f"{ping.mention}", embed=embed)?

boreal ravine
#

yes

#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
ornate lichen
main forum
# boreal ravine yes

Oh i got it, there was a problem somewhere else and I fixed this here already with content=. Thank u 🙂

mental kraken
boreal ravine
mental kraken
last moss
#

hey, im getting a weird error witht his code

#
 file = await attachment.to_file()
            artist = msg.author
            caption = "No caption" if caption == "" else caption
            embed = discord.Embed(description=f"**Caption**: {caption}")
            file = None
            if attachment.is_spoiler():
                file = await attachment.to_file(spoiler=True)
            else:
                embed.set_image(url=attachment.url)
            
            embed.set_footer(text=f"Uploaded by {artist.name} (post unverified)", icon_url=artist.avatar_url)
            embed.colour=self.colour
            embed.add_field(name="Tags", value="-")
            #else:

               # await msg.author.create_dm()
               # await msg.author.dm_channel.send("You cannot upload files that arent images or videos in this channel!")
                #await msg.delete()
            
            message = await galleryChannel.send( embed=embed, file =file)
            
 
#
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\pc\Desktop\Projects\Cool art bot\cogs\artlevels.py", line 105, in on_message
    message = await galleryChannel.send( file =file)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
    return await send(channel, *args, **kwargs)
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\dpy_overrides.py", line 264, in send
    data = await state.http.send_files(
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 185, in request
    async with self.__session.request(method, url, **kwargs) as r:
  File "C:\Users\pc\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 343, in request
    return _RequestContextManager(self._request(method, url, **kwargs))
TypeError: _request() got an unexpected keyword argument 'form
#

You gotta love it when u get an error in a file u didn't even program

ornate lichen
#

i think u need to send ur code lol

slate swan
#

Is it possible to make a bot respond to another bot?

#

if so, what is the script of it?

tiny ibex
#

How can I make my bot leave a server

last moss
#

what?

tiny ibex
#

Yup like I want it to send a message as soon as it joins and then leave the server

#

@last moss

#

There is a thing called code blocks which you should use

last moss
#

!formatting

#

!paste

slate swan
#

It says message.embeds has neither of the functions title and description.. How do I get the title and description from the embed?

tiny ibex
#

Sorry for late reply wifi died

#

@last moss

last moss
#

Why did u tag me tho

#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
last moss
#

yeah there is a guild.leave() method

#

just do that

tiny ibex
tiny ibex
frosty prairie
#

how to do dis

#

showing message to only specific user

tiny ibex
frosty prairie
#

eh?

tiny ibex
#

Which lib are you using?

frosty prairie
#

'-'discord?

tiny ibex
#

IDK how it's done in dispy

frosty prairie
#

uk how to do in disjs?

tiny ibex
frosty prairie
#

then?..

tiny ibex
#

I am using pycord, discord-components and disnake

frosty prairie
#

ahh alright

boreal ravine
frosty prairie
#

ah?..

last moss
last moss
frosty prairie
#

ahh i see alright :/

boreal ravine
#

It's better to use a fork rather than those.

last moss
#

Works fine for me

tiny ibex
last moss
valid niche
tiny ibex
valid niche
#

ephemeral is just the "only one person can see this"

last moss
#

I was replying to the guy who tagged me

tiny ibex
valid niche
#

the only thing discord.py doesn't have is slash commands

last moss
valid niche
tiny ibex
last moss
#

^

boreal ravine
#

dont mislead by the way

#

🙃

frosty prairie
#

thanks ^^

valid niche
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
valid niche
#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
valid niche
last moss
#

didn't know that tbh

valid niche
#

also dropdown

tiny ibex
valid niche
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.

This is usually represented as a drop down menu.

In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Select.values "discord.ui.Select.values").

New in version 2.0.
tame marsh
tiny ibex
last moss
#

i think discord-py-interactions does the job just fine anyway

valid niche
slate swan
#

can someone help me if someone uses a command what they dont have cant use how do i make the bot tell them

valid niche
slate swan
#

how do i do that

tiny ibex
valid niche
tiny ibex
#

Well there are many ways

opaque plinth
#

Yep but easiest us error handler ig?

tiny ibex
opaque plinth
#

Ohh

valid niche
# opaque plinth Yep but easiest us error handler ig?

it's either error handling, which is the easiest and most used way, you can find plenty of examples and such.

The other way is to make the bot tell it's not usable in the check function, and silently ignore the error

tiny ibex
#

Most of the people use error handlers tho

#

IDK why

valid niche
tiny ibex
sage otter
#

because it’s more work.

boreal ravine
tiny ibex
#

First make a command then make an error

#

Like TF

boreal ravine
#

thats just wasting ur time making custom errors imo

valid niche
# tiny ibex Why not use if-else?

because that means having a whole payload of if statements at the start of EVERY SINGLE command, instead of one uniform check function that you only have to write once. And a very well structured error handling function where you can define the behaviour for all commands

#

and you can also write local error handlers for those few commands you want to have different behaviour

tiny ibex
opaque plinth
valid niche
tiny ibex
boreal ravine
#

How do we count how many reactions are on a message?

timber kindle
#

I got my bot online and set a prefix, now I’m just wondering how to find out what I can do with the bot? Like how do I figure out how to make the bot ping a certain person if a command is ran or ban someone?

opaque plinth
valid niche
#

the check system just allows you to easily write a decorator to check if someone for instance has a specific permission, instead of having to write clunky if statement that gets the permissions and checks if the specific permission is in there

tiny ibex
sage otter
tiny ibex
#

But with those which need specific errors

opaque plinth
tiny ibex
#

I used if-else

boreal ravine
opaque plinth
boreal ravine
#

!d discord.Message.reactions

#

a

valid niche
#

the checking of your requirements in the form of checks of if statements or whatever is step one

#

handling the result of that in an error handler is step 2

#

these can be completely separated and changed out

boreal ravine
opaque plinth
river kindle
#

i am creating a database, only the code does not create the table

code:

async def on_ready ():
    db = sqlite3.connect ('my.sqlite')
    cursor = db.cursor ()
    cursor.execute ('''
    CREATE TABLE IF NOT EXISTING main (
      guild_id TEXT,
      message text,
      channel_id TEXT
    )
    ''')```

error:
none from the console, no tables created from SQLITE
boreal ravine
#

IF NOT EXISTS i think?

tiny ibex
sage otter
#

why are you using sync SQLite bruh

boreal ravine
#

mm havent used sql before not sure

river kindle
boreal ravine
#

theres a literal gist on how to get a help command

tiny ibex
sage otter
#

And you don’t need a cursor to execute your bots db schema.

river kindle
boreal ravine
sage otter
#

Just use db.execute

tiny ibex
#

😭

river kindle
boreal ravine
tiny ibex
#

Invite please

tiny ibex
sage otter
river kindle
#

uhm

#

lemme try

sage otter
#

Really you only need the cursor for fetching data.

river kindle
#

nothing happens

#

lol

rotund zinc
#

Can I send here a thing that took me 5 minutes?

boreal ravine
#

yes

sage otter
#

After the execute

rotund zinc
boreal ravine
#

🗿

rotund zinc
#

I love python

boreal ravine
#

same

sick birch
#

agreed

slate swan
#

Why did it happen

boreal ravine
#

u need 2.0

slate swan
#

I have 2.0

valid niche
slate swan
slate swan
valid niche
# slate swan Here

possibly venvs and different installs? otherwise your imports aren't correct

slate swan
#

Exactly

#

How do i fix them

#

When i run
pip -u

valid niche
slate swan
#

How do i fix it

valid niche
#

by either specifying what version to use in the pylauncher (py command), or uninstalling versions you don't use

#

you pip command is on PATH to a specific version of python, but the pylauncher (py command) by default goes to another version

granite pollen
#

I wanna make a discord bot. Where do I start?

dusk dust
#

is there any tutorial explaining how i can create a web control panel? like mee6 or carl

outer violet
#

How do you get the relative time of a user? So like if someone did a user info command and it had when said user joined or whatever it would look like Tues, 20 March 2021 06:44 PM UTC (7mo ago)?

wicked needle
#

So I am trying to make a >clear command, which will either clear a certain amount for either users or just channel. I know how to do the delete for messages in just the channel. But I do not know what check function that is required.

rotund zinc
#

wszystko działa / everything works

#

po prostu smieszny bot / its just a funny bot

wicked needle
#

Nvm I fixed it

timber kindle
#

When I try typing a command on my bot I get this error message

This is my code excluding the import and token

command_prefix = '='
bot = commands.Bot(command_prefix = command_prefix)

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

@bot.command()
async def ping():
  await bot.say("Pong")

bot.run(TOKEN)```
leaden jasper
#

how to wait for a task to cancel

distant tree
#

is there a way to count the time it takes to complete a command?

sick birch
distant tree
distant tree
novel cargo
sick birch
#

datetime.datetime.now().timestamp() will return the current timestamp

novel cargo
#

use the timeit

sick birch
#

That would work as well

timber kindle
#

I get an error when I run a command =ping in my code

command_prefix = '='
bot = commands.Bot(command_prefix = command_prefix)

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

@bot.command()
async def ping():
  await bot.say("Pong")

bot.run(TOKEN)```
#

this is my error

#
Traceback (most recent call last):
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\core.py", line 690, in _parse_arguments
    next(iterator)
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\bot.py", line 979, in on_message
    await self.process_commands(message)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\bot.py", line 976, in process_commands
    await self.invoke(ctx)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\rverm\timer\venv\lib\site-packages\discord\ext\commands\core.py", line 693, in _parse_arguments
    raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for ping command is missing "ctx" parameter.
valid niche
#

and bot.say is nothing

#

bot is just the bot instance, it has no say

#

and if that's meant to send a message, it has no idea on where to send the message

tame marsh
#

in disnake to check message content it is disnake.message.content but in the api it says as argument only startswith how do i check if somewhere in the message is a specific word or sentance?

dusk dust
#

when i restart the bot (in vscode) the "amount" is reset too... how can i make the amount not go out?
I used this public command to test and have a basis on how to create an economy command

amounts = {}

@bot.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} in the bank".format(amounts[id]))
    else:
        await ctx.send("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts:
        amounts[id] = 100
        await ctx.send("You are now registered")
        _save()
    else:
        await ctx.send("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()
valid perch
twilit scarab
#

Good Evening guys!

I want to add some more parameters and make them optional so that the user can add for e.G one added field in the embed, just if he wants he could add a second one. How to make this parameters optional?

@client.command(name='cembed', pass_context=True)
@has_permissions(ban_members=True)
async def cembed(ctx, title, description, name, value):
  embed = discord.Embed(
    title = title,
    description = description,
    colour = discord.Colour.red()
  )
  #embed.set_footer(text='Euer Apocalyptic Serverteam', icon_url='https://cdn.discordapp.com/emojis/864438006953934849.png?size=128')
  #embed.set_image(url='https://media.discordapp.net/attachments/901462338669019156/902961928014553088/oie_wgj4WZr22F9h.gif')
  #embed.set_thumbnail(url='https://media.discordapp.net/attachments/901462338669019156/902933022477791333/0e863f0c17117e606fc1c35ac32276222b2dd96fd4aec223466a4917caefca31a0fe6a17a2b3309ada39a3ee5e6b4b0d3255bfef95601890afd80709e9453722f343b4a9c927610965eea19a.png')
  #embed.set_author(name='Apocalyptic',
  #icon_url='https://cdn.discordapp.com/emojis/864438006953934849.png?size=128')
  embed.add_field(name = name , value = value , inline=False)
  #embed.add_field(name='**§5 Fraktionen**', value='· ', inline=False)
  #embed.add_field(name='**§6 Flaggen**', value='·', inline=False)
  await ctx.send(embed=embed)
  await ctx.message.delete()
@cembed.error
async def cembed_error(ctx, error):
    if isinstance(error, MissingPermissions):
        await ctx.send('Du hast keine Berechtigung diesen Command auszuführen! {0}'.format(ctx.author))

Thx for any help :==)

dusk dust
valid perch
#

Well you'll need to load the file on start and set amounts to it

valid perch
tame marsh
#

thx

valid perch
#

Yea

wicked needle
#

do I use the await delete_messages() the same way as await delete()?

dusk dust
wicked needle
#

Yeah, but do I just type await delete_messages()

#

I got a list

valid perch
#

I assume you havent tried it

scenic moat
#

hi, how do you edit a past message with the id of the message?

elfin pewter
#

bros i want create bot with python but i can that? or i need learn discord.py?

wicked needle
#

Or like await message.channel.deletr_messages()

valid perch
#

Also its a method on a channel, so you need to call it on them

wicked needle
#

Just noticed that function

valid perch
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

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

thanks

valid perch
wicked needle
#

Ima test if it works, brb

elfin pewter
valid perch
#

I will can that on python, can you rephrase this so it makes sense

elfin pewter
#

okay thx

scenic moat
scenic moat
#

it also didnt like the , /

valid perch
#

Its a method on a TextChannel... As shown in the docs

scenic moat
#

which means?

valid perch
#

Object oriented programming, would recommend brushing up on it. Will help

It means you need to call that method on an instance of TextChannel

scenic moat
#

how would you go about doing that?

valid perch
#

!d discord.Client.get_channel

unkempt canyonBOT
scenic moat
#

would you do it as

get_channel(id , /)
fetch_message(id, /)
message.edit(new text)

valid perch
#

Yea

scenic moat
#

okay thanks

slate swan
#

Hello anyone interested in helping me make vouch bot?

twilit scarab
#

Can you help me out with that?

@client.command(name='cembed', pass_context=True)
@has_permissions(ban_members=True)
async def cembed(ctx, title, description, *name1, value1, name2, value2):
  embed = discord.Embed(
    title = title,
    description = description,
    colour = discord.Colour.red()
  )
  #embed.set_footer(text='Euer Apocalyptic Serverteam', icon_url='https://cdn.discordapp.com/emojis/864438006953934849.png?size=128')
  #embed.set_image(url='https://media.discordapp.net/attachments/901462338669019156/902961928014553088/oie_wgj4WZr22F9h.gif')
  #embed.set_thumbnail(url='https://media.discordapp.net/attachments/901462338669019156/902933022477791333/0e863f0c17117e606fc1c35ac32276222b2dd96fd4aec223466a4917caefca31a0fe6a17a2b3309ada39a3ee5e6b4b0d3255bfef95601890afd80709e9453722f343b4a9c927610965eea19a.png')
  #embed.set_author(name='Apocalyptic',
  #icon_url='https://cdn.discordapp.com/emojis/864438006953934849.png?size=128')
  embed.add_field(name = name1, value = value1, inline=False)
  embed.add_field(name = name2, value = value2, inline=False)
  #embed.add_field(name='**§6 Flaggen**', value='·', inline=False)
  await ctx.send(embed=embed)
  await ctx.message.delete()
@cembed.error
async def cembed_error(ctx, error):
    if isinstance(error, MissingPermissions):
        await ctx.send('Du hast keine Berechtigung diesen Command auszuführen! {0}'.format(ctx.author))

I want to add these fields like name1, value1, name2, value2 as optional parameters so the person who invokes the command is able to create just one embed.add_field for e.G

You know how to do that?

timber kindle
#

I'm trying to make a command so I can set a certain command to send a message in a set channel

valid perch
timber kindle
#
@bot.command()
async def announcement(ctx, announcement_text):
  if announcement_channel != "":
    await ctx.send(f"@everyone {announcement_text}")
  else:
    await announcement_channel.send(f"@everyone {announcement_text}")

@bot.command()
async def changeannouncementchannel(ctx, change):
  announcement_channel = bot.get_channel(change)
  await ctx.send(f"Announcement Channel Changed To #{announcement_channel}")```

I don't know why my announcement won't send to the channel I change it to
#

when I try changing it my bot says
"Announcement Channel Changed To #None"

valid perch
#

get_channel returns None

#

Just do
change: discord.TextChannel then you dont need it

timber kindle
#

where would I put that?

dusk dust
#

dude... how do can i add amount to a var?

valid perch
#

Google: "How to read a json file, python"

#

Alternately add the query how to set variable

timber kindle
#
async def announcement(ctx, announcement_text):
  if announcement_channel != "":
    await ctx.send(f"@everyone {announcement_text}")
  else:
    await announcement_channel.send(f"@everyone {announcement_text}")```

Why isn't it sending to the channel I set announcement_channel to?
valid perch
#

You likely dont set it right. Make it a bot var

dusk dust
twilit scarab
#

so the ```py
nextcord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)

"nextcord.ext.commands.flag()" is for example cembed.flag(...) ?
valid perch
#

Im not sure. I've never used it before

timber kindle
#
import discord
from discord.ext import commands

TOKEN = 'My Token'
command_prefix = '='
bot = commands.Bot(command_prefix = command_prefix)
announcement_channel_set = ""
@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(bot))

@bot.command()
async def announcement(announcement_channel_set, announcement_text):
  if announcement_channel_set == "":
    await bot.send(f"@everyone {announcement_text}")
  else:
    channel = announcement_channel_set
    await channel.send(f"@everyone {announcement_text}")
@bot.command()
async def changeannouncementchannel(ctx, change: discord.TextChannel):
  global announcement_channel_set
  announcement_channel_set = bot.get_channel(change)
  await ctx.send(f"Announcement Channel Changed To #{change}")


bot.run(TOKEN)```

This is my whole program, what I don't get is why when I change announcement_channel_set as a global variable, it doesn't change the channel I want the announcement to go into when I do =announcement {message}
valid perch
#

Use bot var's, its way easier

timber kindle
#

idk what bot vars are

valid perch
timber kindle
#
async def announcement(ctx, announcement_text):
  if bot.announcement_channel_set == "":
    await ctx.send(f"@everyone {announcement_text}")
  else:
    channel = bot.announcement_channel_set
    await channel.send(f"@everyone {announcement_text}")```

I have it set to the bot variable, now my only problem is that if I do ``await channel.send(f"@everyone {announcement_text}")`` it wou't work correctly because 'NoneType' object has no attribute 'send'
sage otter
#

So get the channel object?

timber kindle
#

nvm... I fixed it

valid perch
#

if bot.announcement_channel_set == "": -> if not bot.announcement_channel_set

pliant gulch
#

Cogs have there own separate command error handler

#

You should just do them in there

#

!d discord.ext.commands.Cog.cog_command_error

unkempt canyonBOT
#

await cog_command_error(ctx, error)```
A special method that is called whenever an error is dispatched inside this cog.

This is similar to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") except only applying to the commands inside this cog.

This **must** be a coroutine.
pliant gulch
#

You can use a global handler, but this will be every cogs errors

#

Sorry, I do not have the time right now

#

Maybe claim a help channel for the traceback module

#

As it's not directly related to discord bots

vast gale
#

is there a fork of dpy that ppl have mostly jumped to?

brave vessel
vast gale
#

yeah

#

discord is adding a few things tho that need support

#

uh, pycord?

#

oh, pycord/nextcord itself, gotcha

brave vessel
#

besides slash commands

vast gale
#

a few permission bits are coming to the platform

#

wait what is the difference between pycord/nextcord and nextcord/nextcord?

vast gale
#

I can't find pycord...

#

.gh repo pycord/nextcord

#

Well there's a pycord/nextcord repo which is why it was confusing

mortal dove
silent ermine
#

https://github.com/Pycord-Development/pycord
GitHub
GitHub - Pycord-Development/pycord: Pycord, a maintained fork of di...
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API

Linux/macOS

python3 -m pip install -U py-cord

Windows

py -3 -m pip install -U py-cord

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API

junior terrace
#

!e ```py
def job(ctx):
print("gm")

    schedule.every().day.at("01:24").do(job)
unkempt canyonBOT
#

@junior terrace :warning: Your eval job has completed with return code 0.

[No output]
junior terrace
#

F

slate swan
#

how do I get the bot to write to me after sending a command like another user sends a command and after that the bot writes to me that is by id

vast gale
#

@slate swan@silent ermine also seems like disnake is another good one

#

!pypi disnake

unkempt canyonBOT
pliant gulch
#

Lefi is a good one Pepega

#

Joking I'm no where close to done

covert palm
#

yoo

#

How do I do event on guildjoin?

sick birch
hollow agate
#
@client.event
async def on_message_delete(message):
    if message.guild:
        b = DT.datetime.now().timestamp()
        b = int(b)
        with open("data.json") as f:
            data = json.load(f)
        if message.author.id == 503641822141349888:
            return
        if message.author.bot:
            return
        if len(message.content) < 1600:
            time = datetime.now(tz=pytz.timezone('America/Tijuana'))
            formatted = time.strftime("%I:%M %p")
            msgtime = (time - message.created_at).total_seconds()
            logchannel = client.get_channel(872911089258598421)
            am = discord.AllowedMentions(
                users=False,
                roles=False,
                everyone=False,
                replied_user=False,
            )
            await logchannel.send(f'<t:{b}:t> Message by `{message.author}` `({message.author.id})` in {message.channel.mention} has been removed. ({round(msgtime, 2)} seconds after being sent) \n**Content**: {message.content}', allowed_mentions=am)
        if len(message.content) > 1600:
            time = datetime.now(tz=pytz.timezone('America/Tijuana'))
            formatted = time.strftime("%I:%M %p")
            msgtime = (time - message.created_at).total_seconds()
            logchannel = client.get_channel(872911089258598421)
            em = discord.Embed(
                description=f'<t:{b}:t> Message by `{message.author}` `({message.author.id})` in {message.channel.mention} has been removed. ({round(msgtime, 2)} seconds after being sent) \n**Content**: {message.content}',
                color=0x00a8ff)
            await logchannel.send(embed=em)
    else:
        return``` How could I check if there was an image in the message that was deleted and how could I send the image?
sick birch
#

it's just a regular coro decorated with either .event or .listen()

slate swan
#

I want to interact with my server members using a bot so I made this command ```py
@client.event
async def on_ready():
print(f"Connected to {client.user}")
print("----------------------------------------------")
while True:
msg=input("Message: ")
await client.guilds[0].channels[-1].send(msg)

@client.event
async def on_message(message):
if message.channel.id==907782076219154474:
print(f"{message.author}: {message.content}")```

But since the loop is on, on_message event is not working. How can I make so that both the loop and on_message event work together

sick birch
#

check the length, if it's bigger than 0, that means there was an image/video

wicked atlas
hollow agate
#

So if message.attachments > 0?

sick birch
sick birch
#

message.attachments returns a list of attachment objects

#

or you can just do if message.attachments:

sick birch
#

whichever makes more sense to you

hollow agate
#

if len(message.attachments) > 0 xD I think that'll work

sick birch
sick birch
sick birch
slate swan
#

:3

hollow agate
#

Ahh, okay! Thank you :)

sick birch
#

asking for input() is blocking

slate swan
#

yea

sick birch
#

you'd have to do some messy stuff to make it not blocking, not really worth it

hollow agate
#

Then I just do ctx.send(f'{message.attachments}') to send it?

sick birch
#

not a string that you can send like normal

slate swan
#

Isn't there a way so that I can put the input command in a function and run the function and on_message simultaneously

sick birch
#

there are non-blocking ways to get console input, but you'd have to use some external libraries and i think it gets messy quite fast

slate swan
#

😐

sick birch
#

you could theoretically use threading for this

slate swan
#

i tried but IDK how to put on_message in it

sick birch
#

do you really need to send messages from console through your bot though?

hollow agate
#

I'm still super confused on how I can send the images even if it's a string :P

sick birch
#

discord.Attachment objects have a url attribute, you might be able to do something with that

hollow agate
#
for m in message.attachments:
    await ctx.send(f'{m.url}')``` Right?
sick birch
#

you may also be interested in these 3 methods

sick birch
hollow agate
#

True okay, thank you!

sick birch
#

My pleasure

slate swan
heavy folio
sick birch
#

perhaps running flask, or something else

slate swan
#

hmm

hollow agate
#

Is it possible for someone to edit an attachment?

#

Just trying to figure out if I need the image thing for on_message_edit

flint widget
#

How do people usually structure their discord bot projects? Specifically ones that use cogs would be good to see

slate swan
#

can somone give me the right code for a client run token

subtle tusk
#

@surreal current help this man

slate swan
#

that was kinda rude

covert palm
surreal current
sick birch
#

i'm assuming that you're making a message logging system, where it logs deleted messages and edits?

hollow agate
#

Yeah

covert palm
#

where can I find events?

#

I need to use on_guild_join

#

is that a valid event?

subtle tusk
#

@slate swan It's not meant to be Rude @surreal current is the best man for the job

#

I would only send the best of the best

covert palm
#

How to send dm to user?

#

User.send()?

hollow agate
sick birch
hollow agate
#
on_guild_join(member):
   await member.send('Welcome!')```
sick birch
#

await it as send() is a coro

covert palm
#

ye exactly

hollow agate
#

Oh yeah, await it xD

#

Been a long day at school 😅

sick birch
covert palm
sick birch
#

bot.event

covert palm
#

ty

mortal dove
#

So I want to switch my current bot from discord.py to pycord, are there any significant things to be aware of like functions returning differently, different names, or stuff like that?

slate swan
#

This is no where near right?

hollow agate
#

Close enough, on_member_join(member): ig

#

He had the documents so he could've figured it out himself if he did try to yoink my code :D

boreal ravine
sick birch
slate swan
#
import requests
import json
import threading

channelid=907782076219154474

msgurl=f"https://discord.com/api/v8/channels/{channelid}/messages"

headers={'Authorization':'Bot TOKENHERE'}

r=requests.get(msgurl, headers=headers)
msg=json.loads(r.text)
print(msg['content'])```

gives error `list indices must be integers or slices not 'str'`
sick birch
#

msg is a list

slate swan
#

hmm

sick birch
#

not a dict

slate swan
#

:3

sick birch
#

it's like doing

msg = [1, 2, 3, 4]
print(msg['content'])
heavy folio
#

i whitelisted my ip already

slate swan
#

so how can I call the value of content

boreal ravine
heavy folio
#

all?

boreal ravine
#

Yep.

sick birch
heavy folio
#

allow access from anywhere?

boreal ravine
heavy folio
#

wouldnt that make the db easy to hack whatpepe2

sick birch
slate swan
boreal ravine
sick birch
#

it really depends

slate swan
#

ook

sick birch
#

in your case you wouldn't want to do that

slate swan
#

Done I just didpy print(msg[1]['content'])

boreal ravine
#

You only do that with dictionaries

loud junco
#

can someone share me tutorial about classes?

#

w3school is doing some rocket explanation

loud junco
#

thanks

mortal dove
loud junco
#

just give me something that they explain a lot

#

instead of covering __init__ in one sentence

mortal dove
#

the pt1 is assuming you don't know what a class is in the first place

loud junco
#

alright

mortal dove
#

helped me at least ¯_(ツ)_/¯

loud junco
#

thank you

mortal dove
#

if you want, someone here can also help you out with some concepts

#

np

boreal ravine
#

I just pasted the same link oop

loud junco
#

u all like realpython

boreal ravine
#

¯_(ツ)_/¯

wise prairie
#

is there a way to take a message and generate a ctx for it?

#

like, a message the bot sent?

slate swan
unkempt canyonBOT
#

await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Returns the invocation context from the message.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
wise prairie
stoic bridge
#

How do I create a command for my bot the if i type =kill [target] it will send [author] killed [target].? with discord.Client()

boreal ravine
#

!d discord.Message.mentions

unkempt canyonBOT
#

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

Warning

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

stoic bridge
#

oh

#

ty i will try that

mortal dove
#

How does one switch from discord.py to pycord? I have it installed with pip and that's about it.

pale zenith
#

pip install -U modulename

boreal ravine
mortal dove
#

ye I already did that but what's after that? How do I change my code from d.py to pycord? All the imports and syntax looks identical.

final iron
#

import pycord as discord

loud junco
#

is introduceSelf() also an object? or is it a method

silent ermine
# mortal dove How does one switch from discord.py to pycord? I have it installed with pip and ...

https://github.com/Pycord-Development/pycord
GitHub
GitHub - Pycord-Development/pycord: Pycord, a maintained fork of di...
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API

Linux/macOS

python3 -m pip install -U py-cord

Windows

py -3 -m pip install -U py-cord

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API

mortal dove
#

It is a method that belongs to the class, robot.

loud junco
visual island
boreal ravine
silent ermine
loud junco
#

=.=

#

so isit object or method

boreal ravine
#

both I guess

loud junco
#

method is a kind of object?

boreal ravine
#

yes

visual island
#

with your current image it could be a method, or a class, or a function

loud junco
boreal ravine
#

you cant call classes

visual island
#

you can

loud junco
#

;-;

visual island
#

if you have __call__ magic method

loud junco
#

im getting more confused

boreal ravine
loud junco
#

object and method

boreal ravine
loud junco
#

object is variable and method is function?

boreal ravine
visual island
lament mesa
boreal ravine
#

class methods yes

slate swan
#

classes are objects
method are functions of the object

loud junco
#

alright im fked with this method and object thing

lament mesa
loud junco
#

what is an object
classes = object?

lament mesa
#

in python, everything is an object

loud junco
#

bruh

#

wtf is this

slate swan
loud junco
#

why am i here

slate swan
#

hope it's quite clear now

loud junco
#

u do something to do object

boreal ravine
loud junco
#

then its a method?

slate swan
#

yeah kindof

loud junco
#

hmmm ok

slate swan
#

it's a function inside the object

boreal ravine
#

Pain imagine not learning this before using dpy

loud junco
#

function is a bunch of code that u dontn wanna repeat right?

visual island
#

!e

class Foo:
  def hi():
    pass
print(Foo.hi)
unkempt canyonBOT
#

@visual island :white_check_mark: Your eval job has completed with return code 0.

<function Foo.hi at 0x7fcea9b74c10>
slate swan
loud junco
boreal ravine
loud junco
#

but why is everything in python an object

#

=.=

boreal ravine
#

its an object oriented language

visual island
#

everything is based on object base class

loud junco
#

alright

#

idk what is this but imma continue 🥲

visual island
#
class Foo:
  ...

eqivalent to

class Foo(object):
  ...
#

also applied with every other classes

loud junco
#

property is variable within classes?

boreal ravine
#

it isnt a variable

loud junco
#

variable within an object are called attribute

#

wtf is going on

boreal ravine
loud junco
#

that guy said that

#

cs dojo

boreal ravine
#

I mean I guess you could call it that but it isn't

#

attributes are class methods but we call them attributes

loud junco
#

im fked with that tutorial

#

lemme find a new one

visual island
#

this one is the best that I found so far

boreal ravine
#

hey I sent that

loud junco
#

im reading this

#

but why htm

boreal ravine
#

anyways it covers literally the basics of classes

loud junco
#

where is the l

boreal ravine
loud junco
#

LOL ok

slate swan
loud junco
#

im trying

slate swan
#

You're Cool

loud junco
#

to learn something that is very confusing

#

100 names for the same thing

slate swan
#

objects may be confusing at start

loud junco
#

imma learn basic first

#

before i continue to build bot

#

if not u guys gonna suffer

#

🤣 🤣 🤣

boreal ravine
#

ok

mortal dove
#

Would anyone who has a bot with pycord using cogs help me through the process? I already have one in discord.py but I can't seem to get it right for some reason.

boreal ravine
#

What seems to be the problem?

mortal dove
#

I mean my first issue is just my imports. This is what I had, and I tried a bunch of different methods of trying to import slash commands and it doesn't work, even the ones in the examples

#

I installed it already though

boreal ravine
#

Might wanna ask in the support server for more questions.

mortal dove
#

Yeah these are my current imports

import discord
from discord import partial_emoji, reaction, user, emoji, Intents
from discord import Color as c
from discord.ext import tasks, commands
from discord.ext.commands import has_permissions, cooldown, BucketType, MissingPermissions
from discord.ext.commands import slash_command
from discord.ext.commands.core import check
from discord.ext.commands.errors import *
#

Okie

boreal ravine
#

hm

slate swan
dusk pumice
#

What happens if I don't reload cogs?

#

Do I need ti reload the cogs?

sage otter
ornate lichen
#
Task exception was never retrieved
future: <Task finished name='Task-13' coro=<Music.start_nodes() done, defined at /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/dismusic/music.py:22> exception=AttributeError("'Bot' object has no attribute 'lava_nodes'")>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/dismusic/music.py", line 25, in start_nodes
    for node in self.bot.lava_nodes:
AttributeError: 'Bot' object has no attribute 'lava_nodes'```
#
client.event
async def on_ready():
  print("Successfully logged in as {0.user}".format(client))
  game = discord.Game("better type >help")
  await client.change_presence(status=discord.Status.idle, activity=game)
  client.load_extension('dismusic')


bot.lava_nodes=[
    {
        'host':'lava.link',
        'port':80,
        'rest_uri':f'http://lava.link:80',
        'identifier':'MAIN',
        'password':'123456',
        'region':'singapore'
        
    }




]```
zenith basin
slate swan
odd walrus
#

working on a discord bot type of shit
so i want it to try and except indexerror
but im not making it a function so after except indexerror: do i write return? then it will rerun the process and try again

#

@ me when u reply thx

zenith basin
#

help me pls

sullen shoal
zenith basin
#

if you answer you get a lot of stack reputation because I knew user

odd walrus
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
anyone knows this error code

sullen shoal
# zenith basin this

so you basically want to assign new value to a variable when the event is triggered

#

or what

zenith basin
#

So i can't change it for them

#

but i wanna see if they changed it to res

sullen shoal
#

im confused asf
could you explain what you're doing and whats not working

zenith basin
#
import robloxpy
import discord
from discord.ext import commands

@bot.command()
async def verify(message, user):
    num = 10  # define the length of the string
    res = ''.join(secrets.choice(string.ascii_letters + string.digits) for x in range(num))
    user_id = robloxpy.User.External.GetID(str(user))
    user_description = robloxpy.User.External.GetDescription(user_id)
    if user_id == "User not found":
        embed = discord.Embed(title="Verification", description=f"Could not find user {user} input a valid account")
        await message.channel.send(embed=embed)
    else:

        photo = robloxpy.User.External.GetBust(user_id)
        ver_embed = discord.Embed(title="Verification", description=f"Set {user}'s about me to `{str(res)}`")
        ver_embed.set_thumbnail(url=photo)
        await message.channel.send(embed=ver_embed)

        print(user_description, res)

# The part that is not working
        if user_description == str(res):
                    
            comp_embed = discord.Embed(title="Verified",
                                       description=f"You have been verified with the Roblox user {user}")
            comp_embed.set_thumbnail(url=photo)
            await message.channel.send(embed=comp_embed)

The if user_description == str(res): is the part that's not working because user_descripition is not getting updated. How would I update it? The Pyblox library documentation: https://github.com/KristanSmout/RobloxPyOfficial

#

what I am trying to do is check if user_description == str(res)

gloomy coral
#

guys can y'all help me in #help-potato its related to reactions

zenith basin
#

but I am getting the user description that from when command was ran but I want to see if they change to res

sullen shoal
#

have you made sure str(res) and user_description is same

#

looks like im still confused so i will just not waste more time and head out

sullen shoal
#

explain what you're doing, what the function does before asking for help. it helps to direct you to the right way

gloomy coral
stoic bridge
#

a little help here how can i mute and unmute a player?

boreal ravine
boreal ravine
meager smelt
#

To the ones you wanna mute

#

A role that doesnt have perms to chatting

#

Not sure about the timing tho...

stoic bridge
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.
boreal ravine
#

get the member instance > add the role

stoic bridge
#

ok

night seal
#

Hi

#

I have a doubt

#

What is this error? How to fix this?

boreal ravine
#

!global

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

night seal
#

what do i add

#

where do i add

boreal ravine
#

read the command

night seal
#

i did

#

am getting confused

boreal ravine
#

read it

night seal
#

it worked for do many days

#

suddenly it stoped working

visual island
#

if the if message.mentions[0]: block didn't run then user will be undefined

tame marsh
#

(a question to disnake)
with the documentation i cant find how to do it

how do i get the sender ?
i want to define the name of the sender in a string
first ill check if a specific word is in the message (if "word" in message.content)
and after i want to get the sender of the message
and the message id
how do i do this?

boreal ravine
tame marsh
unkempt canyonBOT
boreal ravine
tame marsh
#

but how do i use it that i get the author who matches the if message.content?

boreal ravine
unkempt canyonBOT
maiden fable
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.
maiden fable
#

!d discord.User or this

unkempt canyonBOT
#

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

x == y Checks if two users are equal.

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

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
boreal ravine
#

why user

maiden fable
tame marsh
#

what

boreal ravine
maiden fable
boreal ravine
#

i think hes taking about member

tame marsh
#

yeah

boreal ravine
#

talking*

boreal ravine
tame marsh
#

if a members sends send a specific sentance or word the bot should get the author

maiden fable
#

Okay

#

What if it's sent in DMs

tame marsh
#

and "sender" = this.message.author doesnt work

boreal ravine
#

why dont it

tame marsh
#

idk

maiden fable
tame marsh
#

its python

maiden fable
#

yea

tame marsh
maiden fable
#

Why do u have this.message 🤨

maiden fable
tame marsh
#

sry this.Message

boreal ravine
#

this isnt JS OOP its python

tame marsh
#

nope disnake.Message

boreal ravine
maiden fable
tame marsh
#

this.Message.author

maiden fable
#

😐

boreal ravine
#

burh

maiden fable
#

I won't say anything

tame marsh
boreal ravine
#

u said this

maiden fable
#

I meant.... why did u say this.message

tame marsh
#

yes

boreal ravine
#

what was that for

tame marsh
#

bc i want the author of the if

maiden fable
#

It's message.author, not this.message.author

tame marsh
#

but then i get a rndm author?

#

i want the author who matches the if

night seal
#

But

boreal ravine
#

dude

night seal
#

One problem guys

maiden fable
#

Just make nested if statement....?

tame marsh
#

first ill check if a specific word is in the message (if "word" in message.content)
and after i want to get the sender of the message

maiden fable
boreal ravine
night seal
#

So

maiden fable
night seal
#

Someone joined my server

#

And my bot should greet

boreal ravine
maiden fable
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

night seal
#

Instead it is showing that there is an error there

maiden fable
#

U need members intent

maiden fable
night seal
boreal ravine
tame marsh
#

what do u mean

night seal
tame marsh
#

with multiple statment

maiden fable
boreal ravine
maiden fable
#

Wrong message 😐

boreal ravine
boreal ravine
maiden fable
night seal
maiden fable
#

Well 🤷‍♂️

#

That's what the error says

boreal ravine
#

maybe you tried something on the server owner

night seal
#

But I am the server owner

maiden fable
#

It's just sending messages on member joining

slate swan
#

maybe the user joined some other server

maiden fable
#

Member*

#

Lol

night seal
#

what memer

#

member?

slate swan
#

lol yea , user -> joined a server -> member!

maiden fable
#

Not saying anything to u @night seal

boreal ravine
# night seal

Also please use the commands extension if you wanna make commands, dont use events for making commands

night seal
#

ok

#

Thank you all

ornate lichen
maiden fable
#

What's the railway thing 🤨 @ornate lichen

boreal ravine
maiden fable
#

Ah, okay

dusk dust
#

how can i do this with the bot? (the person type the command and the bot click on reply and type the code

#

don't explain yourself very well.... that's basically it

slate swan
#

is it possible to add inbuilt checks as global checks?

slate swan
# maiden fable Wym

like adding bot_has_permissions as a global check
if i try that the code runs without any error , but the check does not get implemented

maiden fable
#

U tried bot.check?

slate swan
#

yea

#

both bot.check and bot.add_check

maiden fable
#

Can I see how u did that?

slate swan
#

yea , if i try making a custom check instead it works

slate swan
maiden fable
#

Did you import those classes/functions from commands namespace or something?

slate swan
#

nah py from disnake.ext.commands import Bot , when_mentioned_or , bot_has_permissions

maiden fable
#

Yea that's what I meant lol

#

BTW, why do u even wanna do it a bot check?

#

Its gonna raise a CheckFaliure error anyways

slate swan
#

oh , not a BotMissingPermissions error?

maiden fable
#

I don't think so

#

Wait it totally depends on the exception hierarchy

slate swan
#

mhm BotMissingPermissions comes under CheckFailture

unkempt canyonBOT
slate swan
#

in my opinion ,. yes

#

its well maintained and documented

#

cool :3

boreal ravine
#

Nice

slate swan
visual island
#

you can actually use it for your account

#

but almost everything about it is deprecated

slate swan
#

and breaks the tos

boreal ravine
#

😳

loud junco
#

after i finish class

#

what do i need to learn

boreal ravine
loud junco
boreal ravine
loud junco
#
static void UpdatePresence()
{
    DiscordRichPresence discordPresence;
    memset(&discordPresence, 0, sizeof(discordPresence));
    discordPresence.state = "In an ender dragon fight";
    discordPresence.details = "Where is my water bucket???";
    discordPresence.largeImageText = "RPMinecraft";
    discordPresence.smallImageText = "Rogue - Level 100";
    discordPresence.partyId = "1";
    discordPresence.partySize = 69;
    discordPresence.partyMax = 420;
    Discord_UpdatePresence(&discordPresence);
}
```how do i change this to python
#

this is javascript right?

boreal ravine
#

since thats for games

loud junco
#

def UpdatePresence():
DiscordRichPresence discordPresence
memset(&discordPresence, 0, sizeof(discordPresence))
discordPresence.state = "In an ender dragon fight"
discordPresence.details = "Where is my water bucket???"
discordPresence.largeImageText = "RPMinecraft"
discordPresence.smallImageText = "Rogue - Level 100"
discordPresence.partyId = "1"
discordPresence.partySize = 69
discordPresence.partyMax = 420
Discord_UpdatePresence(&discordPresence)

#

is this how i do it?

#

or nah

boreal ravine
#

no wtf

loud junco
#

idk how to change it

boreal ravine
#

you dont just change stuff and expect it to work

loud junco
#

🤣

#

=.=

boreal ravine
#

What are you looking for

loud junco
#

im trying to change that to python

#

this is what i got there

#

:(

boreal ravine
boreal ravine
loud junco
#

static void means function or what

boreal ravine
#

Whats the error

boreal ravine
#

Well if the interaction says that theres probably gonna be an error.

#

Do you have an error handler?

#

👍

#

Hm

#

A third party lib

maiden fable
#

So

#

Just Rick Roll them whenever they button click in an ephemeral message

maiden fable
#

Yea

boreal ravine
#

I could, but I don't really know much about thirdy party libraries

waxen granite
#
        async for guild in self.bot.fetch_guilds(limit=100):
                guildmsg += f"**{counter}:** **Name:** {guild.name}\n  **ID:** {guild.id}\n  **Created at:** {guild.created_at.strftime('%b %d, %Y')}\n  **Owner:** {guild.owner.name}``` 
guild.owner.name gives nonetype error. how can i get the guild owner name here?
visual island
#

member intents enabled?

magic ore
#

Also you generally shouldn't use fetch_guilds

#

Assuming you have the guilds intent enabled (which is on by default) and this is after the bot is ready, use the guilds attribute of your bot

#

!d discord.Client.guilds

unkempt canyonBOT
#

property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
loud junco
#

when to use @commands.command

#

when to use @bot.command

dapper cobalt
dapper cobalt
loud junco
#

just use heroku or replit there are 100% free

magic ore
#

Heroku and replit should not be used as bot hosts

#

It doesn't overuse resources depending most of the time

#

Depends on how much ram and memory your server has too

loud junco
#

what is cogs

#

class?

heavy folio
#

hey i need some help with mongodb ```py
@commands.command()
async def auc(self, ctx):
guildid = ctx.guild.id
userid = ctx.author.id

    if collection.count_documents({"guildid": guildid}) == 0:
        collection.insert_one({"guildid": guildid, "userid": userid, "points": 0})
    
    points_count = collection.find_one({"guildid": guildid, "userid": userid, "points": 1})

    for x in points_count:
        before_points = points_count["points"]

    new_points = before_points + 1

    old_data = {"guildid": guildid, "userid": userid}
    new_data = {"$set": {"points" : new_points}}

    collection.update_one(old_data, new_data)

    embed = discord.Embed(
        description=f"**Thanks {ctx.author.mention} for conducting the auction!** \nYou are awarded with an extra point, your total auction point is: {new_points}"
    )
    await ctx.send(embed=embed)
    await ctx.message.delete()
hollow sedge
#

what is the best way to sync a github linked heroku repo to its original github repo?

tawdry perch
#

Why does this not set a slowmode to channel? There is no any error messages and last ctx.send is sent but nothing channe in the channel```py
@commands.command(aliases=["sm", "smode", "slow"])
async def slowmode(self, ctx, *, duration: int):
"""Sets slowmode to current channel the commands is invoked, arguments taked as in seconds"""
await ctx.channel.edit(slowmode=duration)
await ctx.send(f"Slowmode set to {duration} second(s)")

dapper cobalt
tawdry perch
#

there are free ones?

loud junco
#

advertise

#

:)

dapper cobalt
tiny ibex
#

🤣😂

dapper cobalt
#

I repeat.

tiny ibex
#

No doubt it's really good but it's really expensive

maiden fable
#

Tf's happening here 🤨

tiny ibex
#

I am jk

mortal turret
tawdry perch
#

Why does this not set a slowmode to channel? There is no any error messages and last ctx.send is sent but nothing change in the channel```py
@commands.command(aliases=["sm", "smode", "slow"])
async def slowmode(self, ctx, *, duration: int):
"""Sets slowmode to current channel the commands is invoked, arguments taked as in seconds"""
await ctx.channel.edit(slowmode=duration)
await ctx.send(f"Slowmode set to {duration} second(s)")

tiny ibex
tawdry perch
#

I see

tiny ibex
#

It's slowmode_delay

dapper cobalt
mortal turret
tiny ibex
#

😬

mortal turret
#

its not free Ke

tiny ibex
#

It is free

dapper cobalt
#

He asked if there are free ones, and I replied with that. Might be a Your English probelm.

mortal turret
#

bro?

#

you said its free and its literally not free

tiny ibex
#

Just that you will have to pay higher electricity bills

dapper cobalt
tiny ibex
#

😂

mortal turret
#

yeah i know u advertise it as free but when you click free hosting you are prompted to donate in your discord server

dapper cobalt
#

You can donate.

mortal turret
#

or gain “points”

tiny ibex
mortal turret
#

it isnt free

tiny ibex
#

That's why I left

slate swan
dapper cobalt
#

Let's either continue that either in DMs, or just close the case.

tiny ibex
slate swan
#
points.generate()
dapper cobalt
tiny ibex
slate swan
#

Yeah that's my point xD

mortal turret
#

nice scam boilerplate website @dapper cobalt dogeweird

tiny ibex
#

🥺

tiny ibex
#

🥺

loud junco
#

thats gonna trigger sherlock

mortal turret
#

heroku is good

loud junco
#

LOL

tiny ibex
slate swan
#

well it doesn't suck

loud junco
slate swan
#

not for discord bots atleast

tiny ibex
#

Heroku sucks a lot

slate swan
#

for discord bots, it does

mortal turret
#

heroku better than this guys scam hosting service

tiny ibex
#

But it's good cuz it's free