#discord-bots

1 messages Ā· Page 507 of 1

boreal ravine
#

use message.author

tropic briar
#
@client.command()
async def ban(message, member: discord.Member, *, reason=None):
    await message.send("hmm")
    await member.ban(reason=reason)
    await message.send('A member has been banned')
boreal ravine
#

error?

tropic briar
#

It's not even sending the message

tropic briar
boreal ravine
#

wtf

#

wasnt it an event?

boreal ravine
tropic briar
#

Oh wait

#

I showed you a different function

boreal ravine
#

why is there message in the command tho

#

use ctx for commands

#

and use certain params for events

sacred folio
#
def check(reaction, user):
      if (str(reaction.emoji == emoji_yes) and client.user != user):
          return reaction.users()

reaction, user = await client.wait_for('reaction_add', check=check)

I use this to handle players that react on an embed.

tropic briar
#
@client.event
async def on_message(ctx, message, member):
  for i in range(len(Filter)):
    if Filter[i] in message.content:
      for j in range(1):
        await member.ban(reason='filter')
        await message.send('A member has been banned')
boreal ravine
visual island
#

on_message only takes message

tropic briar
#

Ok ok I will remove it

visual island
#

remove member too

sacred folio
#

If im not mistaken, am i supposed to use on_reaction_remove in the same way and just have another wait_for? This part is puzzling me

tropic briar
#
@client.event
async def on_message(message, member):
  for i in range(len(Filter)):
    if Filter[i] in message.content:
      for j in range(1):
        await member.ban(reason='filter')
        await message.send('A member has been banned')
``` I have to go now
slate swan
#

How do I do this?
Those hidden messsage thingys.

#

i'd rather use on_raw_reaction_remove

#

correction... message.channel.send

#

message in his function is used as is message object

#

not context

#

what??

#

that would ban the person who triggerd the command

#

bruh

boreal ravine
#

not a command

#

an event

boreal ravine
slate swan
#

message.author*

boreal ravine
#

when did i say that?

#

i never said that member.author

sacred folio
#

On raw reaction remove? I did try that but couldnt get it to work, all i got it to tell me was that there was no member, users wasnt an option either as it is in reaction_add

slate swan
boreal ravine
slate swan
#

also u need reaction intents to make sure it actually works

#

the param for it is only payload

boreal ravine
#

there are intents for that?

#

aren't there only 2 intents

slate swan
#

.-.

#

there is intents for almost every thing that cant be stored on a internal cache when its offline

boreal ravine
#

only 2

slate swan
#

BRUH DIS MAN

#

🤣

boreal ravine
#

im not a man

#

please stop calling me that

slate swan
#

!d discord.Intents.default

unkempt canyonBOT
#

classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members").
slate swan
#

Only presences and members need to be enabled manually

#

^

sacred folio
#

That feels so weird

slate swan
#

I usually just do discord.Intents.All() so I dont have to worry about the ones disabled

#

Same

sacred folio
#

So i dont need intents to handle when someone reacts on the embed, but i need them for when someone removes their reaction?

slate swan
#

not just those 2

#

like raw_on_message_delete or smth

#

think that's should be the name

#

There's also reaction intents iirc

#

there is a whole section for it in the api reference

sacred folio
#

Hmm, if there is a reaction_add, why isnt there just a reaction_remove

slate swan
#

!d discord.Intents.reactions

unkempt canyonBOT
slate swan
#

As well as emojis

#

These

sacred folio
#

Okay so step 1,get all intents so all gateway events are available

sacred folio
#

Then i need a new async def for the on raw reaction remove with payload as its only parameter

#

Can i create that locally within the command or does it have to be completely separate

vagrant brook
#

You can use wait_for if you want it to be in a command

sacred folio
#

I couldnt get it to work

#

But yeah, i would like it in my command

valid perch
#

Well it is wait_for, so if you can show us what you tried we can help

sacred folio
#
def check(reaction, user):
      if (str(reaction.emoji == emoji_yes) and client.user != user):
          return reaction.users()

reaction, user = await client.wait_for('reaction_add', check=check)

I use this to handle players that react on an embed.

#

And it works, i can update the embed

valid perch
#

Check needs to return True / False

valid perch
#

wait_for will only give you your value back when check returns true

sacred folio
#

Oh okay

#

Because i basically set up the same wait for structure for my remove

high flame
#

that's wrong too

#

str(reaction.emoji) == emoji_yes

sacred folio
#

Oh wow, ill fix that

#

Now add doesnt work either

high flame
#

show what you did

broken dirge
#

Does anyone know how to set an activity status?

sacred folio
#
def check(reaction, user) :
    if(str(reaction.emoji) ==  emoji_yes and client.user! = user):
    return True

while True:
    reaction, user = await client.wait_for('reaction_add', check=check) 
broken dirge
#

Do you guys know what library do you need for activity command

slate swan
#

you don't need a library

slate swan
unkempt canyonBOT
#

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

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

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

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

• [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
sacred folio
#

I dont understand the check, it works when i return reaction.users()

tropic briar
#
client = commands.Bot(command_prefix='.')
Filter = ['giant', 'hi', 'hello', 'monke', 'bye', 'balance']
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)


@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.idle, activity=discord.Game('Hello there!!'))
    print('Bot is ready')
    print('Bot is now Online')


@client.event
async def on_message(message, member):
  for i in range(len(Filter)):
    if Filter[i] in message.content:
      for j in range(1):
        await member.ban(reason='filter')
        await message.send('A member has been banned')

@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)
    await ctx.send('A member has been Kicked')


@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
    await ctx.send("hmm")
    await member.ban(reason=reason)
    await ctx.send('A member has been banned')


@client.command()
async def setdelay(ctx, seconds: int):
    await ctx.channel.edit(slowmode_delay=seconds)
    await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")


@client.command()
async def clear(ctx, amount=5):
    await ctx.channel.purge(limit=amount)


@client.command()
async def delete(ctx, message):
    await ctx.channel.delete(message)
#

No command is working

#

Not a single one

slate swan
tropic briar
#

Ok lemme try

valid perch
lean tinsel
#

can someone explain how the sliding windows works?

#

like I am 5

sacred folio
#

Im on a scuffed setup where i can only have discord on my phone, any indentation or misspelling is from me manually typing it in my phone. But i did try returning true and false after the if statement. It didnt work

#

Returning true or false in the check*

mortal thistle
#

hey

#

there is a problem

#

when I run my code in VS Code

#

it's working fine

#

but when I run my code on replit it starts giving me errors

gloomy coral
#

This shows error

#
subreddit=reddit.subreddit("memes")  
        top=subreddit.top(Limit= 5) 
        for submission in top:
            print(submission.title)```
#

shows no limit found

#

shld i use praw or async praw

waxen python
#

async if you can

grim oar
#

you must

waxen python
#

So i have my bot running some moviepy things, some video converting things and general tools, when these finish running, im left with quite a high memory usage, is there a way to clear this?

gloomy coral
#

alright

#

Hi, im using async praw to get memes and it works...

#

but its too slow what can i do?

waxen python
#

use aiohttp instead

#

to get the image and link and title

maiden fable
#

Raw GET requests with aiohttp

waxen python
#

yeah

waxen python
#

well its probably because the scripts that im using are meant to run once then terminate. Can i clear them out of my bot?

gloomy coral
#

idk how to do tht, isnt praw easier?

waxen python
gloomy coral
#

Here is my code

#
@commands.command(aliases=['Meme'])
    async def meme(self,ctx):

        
        subreddit=await reddit.subreddit("memes") 
        all_subs = [] 
        top=subreddit.top(limit= 50) 
        async for submission in top:
            all_subs.append(submission)

        random_sub=random.choice(all_subs)
        name=random_sub.title
        url=random_sub.url
        em=discord.Embed(title=name,color=discord.Color.random())
        em.set_image(url=url)
        await ctx.send(embed=em)```
waxen python
grim oar
#

It should get terminated the point the program ends, is there something which is keeping it alive

waxen python
#

I dont think so

grim oar
#

Hmm

#

idk try forcing gc, tho chances are low that anything will be changed

waxen python
#

import gc

then gc.collect()? or something else?

grim oar
#

Yeah

waxen python
#

ight

#

does that dump it to a file or?

grim oar
#

No

waxen python
#

just it just get yionked

grim oar
#

It unloads the weakx and other objects with 0 refs from the memory

waxen python
#

ok cool, i dont want it saved.

grim oar
#

It doesn't work like that

waxen python
#

i think it helped a little but im not sure if thats just a placebo

grim oar
#

Hmm yeah idk then

slate swan
#

hi

waxen python
grim oar
#

np

west escarp
#

Please do not request help with NSFW services here

slate swan
#

hey so i am trying to make a search command for my bot of a site using selenium but the site is not having a search url site and search button its just search website and you have type and you will get result
there are the codes

driver = webdriver.Chrome()
driver.get('link/search')
searchbox = driver.find_element_by_xpath('/html/body/div/div/div/div[7]/nav/div/div[3]/div/div[1]/input')

slate swan
#

idk what to do anymore because selenium docs have search.button

west escarp
#

It's alright. I would suggest learning this on a site more appropriate then applying it elsewhere, so you can actually get decent help

slate swan
west escarp
#

You can, but without linking or providing any evidence of what site (to comply with our rules about sfw content). And by doing that, you're likely to have issues actually solving your issue.

slate swan
#

I want to make search command for my discord of a site using selenium
(site doesnt have search result url site or search.button)

codes:
driver = webdriver.Chrome()
driver.get('link/search')
searchbox = driver.find_element_by_xpath('/html/body/div/div/div/div[7]/nav/div/div[3]/div/div[1]/input')

#

now?

grim oar
#

Uhh That's not related to discord bots so ig best place to ask wud be #web-development

slate swan
slate swan
grim oar
#

But still, your chances of getting help here regarding non dbot topics (like that) is very low, you should ask in #web-development

grim oar
#

np

sacred folio
#

Does anyone definitively know if wait_for can handle on_reaction_remove?

gloomy coral
waxen python
#

why are you looking through the top 50 then

gloomy coral
#

uh idk, ppl can run it again and again right

#

i dont wanna have only 5 memes

waxen granite
#

is there a way to automatically get the missing permission required by the bot?

#

in on_command_error

boreal ravine
#

the bot missing perms or you

waxen granite
#

bot

slate swan
#

!d discord.ext.commands.BotMissingPermissions

unkempt canyonBOT
#

exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the bot’s member lacks permissions to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
waxen granite
#

in commands.botmissingpermission, how do i get the Permission that is required?

boreal ravine
#

just send the error

waxen granite
#

the perm name

boreal ravine
#

hm

slate swan
waxen granite
#

sure

slate swan
waxen granite
#

can a bot owner use commands for which he does not have guild permission?

tough wagon
waxen granite
#

how about i do a ownerCheck?

#

then?

tough wagon
#

eh

#
def owner_or_permissions(**perms):
    original = commands.has_permissions(**perms).predicate
    async def extended_check(ctx):
        if ctx.guild is None:
            return False
        return bot.owner_id == ctx.author.id or await original(ctx)
    return commands.check(extended_check)```
#

like this @waxen granite

waxen granite
#

ye

#

it will work right?

tough wagon
#

there is more examples in next message @waxen granite

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`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") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent 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").
heavy radish
#

How do I delete the authors message?

maiden fable
maiden fable
tough wagon
heavy radish
#

Thank Youu

maiden fable
magic mica
#

Hey guys,
I am making a discord.py bot. The problem is that, whenever I run it, an error comes up. The error is -
SyntaxError- await outside function

slate swan
slate swan
maiden fable
tough wagon
magic mica
tough wagon
magic mica
#

ok

tough wagon
#

that's python syntax

steep estuary
#

how to fetch and then edit a row in asyncpg discord.py ?

#

postgres

#

:/

heavy radish
#

Question: Is there a BOT version of this?? member: discord.Member

#

or will this do for all

hasty iron
#

what do you mean

visual island
#

bot version?

slate swan
heavy radish
#

Yes

#

Like a command where it wont work if you mention members

slate swan
visual island
#

before_invoke would do I think

heavy radish
#

Hm

slate swan
#

inside the command

heavy radish
#

Okay thank you

full valley
#

Hey guys, I’m trying to make like a queue of some sorts. So players can use !q, and then the q will remember the player and become 1/6, then another player will q and it will become 2/6.. etc.

visual island
#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

heavy radish
#

F

slate swan
#

what are you trying to do?

heavy radish
#

So I want to add a temprole

slate swan
#

can you be more specific about the term 'temprole'

heavy radish
#

a temporary role

#

for a set amount of time

slate swan
#

which gets removed after some time?

heavy radish
#

yes

#

Keep Ping On

slate swan
#

for how long? if its for a short time py asyncio.sleep() will work

heavy radish
#

Like

#

1h

#

max a day

slate swan
#

you would be using a database

visual island
#

a db, with tasks.loop

heavy radish
#

ohh

slate swan
#

to store time when to remove the role

heavy radish
#

I don't have a data base

visual island
#

make one

hasty iron
#

then get one

visual island
#

its not that hard

heavy radish
#

How do I make one?

slate swan
#

use aiosqlite probably

slate swan
hasty iron
#

you dont make a db, you use one

visual island
slate swan
#

its not something you can just make like /makedb

#

it takes time lmao

heavy radish
#

Hm

#

I'll figure this out tomorrow

void mortar
#

!h discord.ext.commands.Command.call

heavy radish
#

Need to sleep

visual island
#

AG_LoliShrug they understand the point, dont they?

visual island
hasty iron
#

they are?

visual island
#

oh

full valley
#

Any ideas guys i’m kinda struggling, don’t know where to find help.

hasty iron
#

!d discord.ext.commands.Command.call

unkempt canyonBOT
#

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

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.

New in version 1.3.
slate swan
#

Hi I have a bot that I'm using to change permissions for a role when a channel is created. However my bot runs into forbidden 403 error. When I explicitly enable the manage permissions for everyone role my bot is able to execute the command (I'm using a listener for channel edits as well). My bot has manage channel permissions serverwide and I'm using discord.py.

valid niche
slate swan
#

it doesnt have the perms to do it

slate swan
#

but i get discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

valid niche
slate swan
#

when I enable manage permissions explicitly it works

valid niche
slate swan
sacred folio
#
def check(reaction, user):
Ā Ā Ā Ā Ā  return str(reaction.emoji) == emoji_yes and client.user != user

while True:
Ā Ā Ā  Ā Ā Ā  reaction, user = await client.wait_for('reaction_add', check=check)
Ā Ā Ā Ā Ā  reaction, user = await client.wait_for('on_reaction_remove',
check=check)

When the last line is added everything stops working. Anyone that knows the proper way to make both actions work?

slate swan
valid niche
valid niche
slate swan
vocal shoal
#

is there an event that triggers when the bot get shutdown/killed?

slate swan
#

i thought its the manage channels that is

#

wait it does have manage roles

visual island
valid niche
vocal shoal
#

ok thx šŸ‘

sacred folio
#

@valid niche its all being handled inside of a command

hasty iron
heavy radish
#

Is discord BOTs considered virtual servers or web hosting?

#

or domains

slate swan
#

definetly not a domain

heavy radish
slate swan
#

trying to find a good but cheap vps

heavy radish
#

Hmm...What would you recommend me

#

Its a small bot

slate swan
#

idk tbh

heavy radish
#

Public server use

#

F

#

Pebble seems nice as I can run my code there and everything is online. But they recommend not using that

#

I need to talk to some experts here

#

Pebble is $3 a month

past ermine
#

is there a way to make it a prefix if the bot gets mentioned

maiden fable
#
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host API:443 ssl:True [SSLCertVerificationError: (1, '[SSL: 
CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)')]

Yo anyone here knows about this error when I try to connect to my API? (aiohttp)

It worked till yesterday and is still working on my main bot

waxen granite
#

how do i get the member.name from role.members?

maiden fable
#

use a loop

waxen granite
#

member.name for member in role.members like this?

lament mesa
maiden fable
#

Yea I was seeing that only haha. Thanks!

waxen granite
visual island
#

list() it

waxen granite
#

elif option.lower() == "bt": role = discord.utils.get(guild.roles, name = "BankTime") await ctx.send(member.name for member in role.members)

visual island
#

or just directly [member.name for member in role.members]

waxen granite
#

ok

high flame
#

or wait

#

would that work?

waxen granite
#

done

#

ye

visual island
#

no, and yes

high flame
#

it will print many time i guess

#

because you aren't doing [] around it

visual island
#

no, it will print generator object

high flame
#

ah

#

list(generator) then

visual island
#

as _ for _ in _ is something that yields

#

so its a generator

lament mesa
waxen granite
#

','.join(member.name for member in role.members) it works

tropic briar
#
@client.command()
async def clear(ctx, amount=5):
         await ctx.channel.purge(limit=amount)
#

Why is clear command not working

visual island
#

Errors?

tropic briar
#

No

#

I think because I have hosted it

boreal ravine
#

why do u always not have errors?

lament mesa
tropic briar
#

I am not checking rn but there were not errors before

hasty iron
#

list comp is faster

tropic briar
lament mesa
#

no.

waxen granite
hasty iron
#

list comprehension

tropic briar
waxen granite
#

oh

boreal ravine
waxen granite
#

is there a link for it?

boreal ravine
#

It works. So how did urs not work?

tropic briar
#

Ya that was fast

tropic briar
#

Lemme check again

#

It's not working

#

And That happened after I hosted my bot on replit.com

visual island
#

replit is not even a hosting service

boreal ravine
#

@tropic briar did u restart ur bot

slate swan
#

broken indent?

boreal ravine
#

nope

visual island
#

they said they didnt get any errors

boreal ravine
#
@client.command()
async def clear(ctx, amount=5):
  await ctx.channel.purge(limit=amount)```
his indents big tho
boreal ravine
slate swan
boreal ravine
#

an indent problem

#

Probably

  1. He didnt restart the bot
  2. Permissions
waxen granite
#

in on_guild_role_update , how can i log the permission that was updated?

visual island
#

after.permissions I think

waxen granite
#

do i need to do the difference of before and after perms?

lament mesa
waxen granite
#

or just afterperms will work?

crystal cliff
#

Anybody got on_member_join channel msg code pls, that works in py pls?

slate swan
#

AttributeError: 'NoneType' object has no attribute 'is_playing'

crystal cliff
visual island
#

what? Bots can't join dm?

#

and group chats

crystal cliff
#

When members join, it sends a welcome msg lol

lament mesa
#

selfbot lemon_thinking

slate swan
slate swan
#

ez

slate swan
#

AttributeError: 'NoneType' object has no attribute 'is_playing'

waxen granite
#

@visual islandwhat about the text channel perms?

slate swan
#
voice_client = ctx.guild.voice_client
try:
            await voice.connect()
except:
            pass
if voice_client.is_playing():
  do something```
tropic briar
slate swan
#

What is wrong?
PS C:\Users\AntiWTap> & C:/Users/AntiWTap/AppData/Local/Programs/Python/Python39/python.exe c:/Users/AntiWTap/Desktop/Bot.py
Traceback (most recent call last):
File "c:\Users\AntiWTap\Desktop\Bot.py", line 118, in <module>
async def warn(ctx, member : discord.Member, *, reason=None):
AttributeError: 'Command' object has no attribute 'Member'
PS C:\Users\AntiWTap>

@bot.command()
async def warn(ctx, member : discord.Member, *, reason=None):
if ctx.author.permissions_in(ctx.channel).ban_members:
embed=discord.Embed(title="Warned", description=f"Du hast {member} gewarnt", color=0xff6600)
await ctx.send(embed=embed)

    user = await bot.fetch_user(870241231555399692)
    await user.send(f"[{member}] wurde von [{ctx.author}] wegen [{reason}] gewarnt")
stark bobcat
#

server_setup is a file

#

py file

#

and i tried to import it

tropic briar
#

Np I will try to fix it on my own

stark bobcat
#

why doesn't it work

visual island
quasi pawn
#

is vultr okay for hosting?

visual island
waxen granite
#

embed.add_field(name = "old perms", value=before.permissions) embed.add_field(name = "new perms", value=after.permissions) whats wrong?

stark bobcat
slate swan
#
voice_client = ctx.guild.voice_client
try:
            await voice.connect()
except:
            pass
if voice_client.is_playing():
  do something```

AttributeError: 'NoneType' object has no attribute 'is_playing'
visual island
stark bobcat
visual island
stark bobcat
#

inside cogs

visual island
visual island
slate swan
#

i will try

stark bobcat
#

@visual island

visual island
stark bobcat
#

it's defined

lament mesa
#

Don't use globals.

stark bobcat
waxen granite
lament mesa
visual island
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.

stark bobcat
#

oh

waxen granite
stark bobcat
visual island
visual island
stark bobcat
visual island
waxen granite
visual island
stark bobcat
stark bobcat
visual island
visual island
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

stark bobcat
#

oh

waxen granite
# visual island .all it maybe?

embed.add_field(name = "old perms", value=discord.Permissions(before.permissions.all))
File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\permissions.py", line 99, in init
raise TypeError('Expected int parameter, received %s instead.' % permissions.class.name)
TypeError: Expected int parameter, received method instead.

full valley
visual island
waxen granite
#

embed.add_field(name = "old perms", value=before.permissions.all) embed.add_field(name = "new perms", value=after.permissions.all) like this then?

visual island
#

mhm

#

or .all()

waxen granite
visual island
#

call it

#

all()

waxen granite
#

wait

visual island
#

bruhhh

waxen granite
#

if i add/remove 1 or more perms, i want only those perms to be listed

visual island
waxen granite
#

while logging

#

like this

visual island
#

hm, after.permissions.manage_channels

#

etc

waxen granite
#

so i got to list all the perms seperately?

visual island
#

mm, maybe? not sure

hasty iron
#

you can iterate through a Permissions object

tranquil cape
#

dpy 2.0a has support for lists and buttons?

#

and slash commands too?

#

if not what lib do you guys prefer for the above

waxen granite
#

how do i check if the perm is True or False?

visual island
tranquil cape
#

oh then what do you prefer for slash

visual island
chilly wadi
#

what is python

#

why im here

maiden fable
#

Bruh

strong kettle
#

How i can send file

chilly wadi
#

Is it python a game, or food?

strong kettle
chilly wadi
#

?

strong kettle
#

programming language

chilly wadi
#

Thanks.

maiden fable
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

visual island
chilly wadi
visual island
#

I know AG_LoliShrug

waxen granite
#
        if before.permissions != after.permissions:
            diff = list(set(after.permissions).difference(set(before.permissions)))
            for changed_perm in diff:
                if changed_perm[1] == True:
                    embed.add_field(name = "Added Permission(s):", value = changed_perm[0], inline =  False)
                elif changed_perm[1] == False:
                    embed.add_field(name = "Removed Permission(s):", value = changed_perm[0], inline  = False)
                await logChannel.send(embed = embed)```
when i add multiple perms it add multiple fields in the embed, how do i add them under a single field?
#

how do change the for line

maiden fable
#

U should use join

#

Do u know str.join()?

waxen granite
#

idk

maiden fable
#

!join

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
half briar
#

FFmpegPCMAudio how to install

waxen granite
maiden fable
#

What's changed_perm?

waxen granite
#

the perm i add/remove

hasty iron
#

and check value?

#

and send perm if value is True

waxen granite
#
            for perm, value in diff:
                if value == True:
                    embed.add_field(name = "Added Permission(s):", value = perm, inline =  False)
                elif value == False:
                    embed.add_field(name = "Removed Permission(s):", value = perm, inline  = False)```
#

@hasty ironlike this?

hasty iron
#

sure

#

does it work?

#

also you dont need to do list(...)

#

diff = list(set(after.permissions).difference(set(before.permissions))) here

waxen granite
#

then?

hasty iron
#

a set is an iterable

#

like a list

#

diff = set(after.permissions).difference(set(before.permissions)) is enough

waxen granite
#

it did not work

#

it creates a field for each perm

#

like before

hollow mortar
#

hey i need help here

hasty iron
#

well yes?

hollow mortar
#
@bot.event
async def on_message(message):
    f = open("badwords.txt" , "r")
    liness = f.read()
    if message.content.lower() in liness:
        await message.delete()
        await message.channel.send("You Cant Say That")
    await bot.process_commands(message)```
hasty iron
#

read your code

waxen granite
#

how do i avoid it?

#

thats why i am here 😦

hollow mortar
#

this code works but if i say a word in the badwords file it only remove the msg that have only the word

hasty iron
#

make 2 lists, one for the removed permissions and the other for the added

#

and then add_field and join the list

hasty iron
hollow mortar
maiden fable
#

Ah

waxen granite
hasty iron
#

yes, and if value is True append perm to list1, otherwise append to list2

maiden fable
#

if any(word for word in lines if message.content.lower() == word): should work

hollow mortar
hollow mortar
#

remove the if msg content.lower right

hasty iron
#

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually

maiden fable
#

Yea

hollow mortar
#

and replace it with that one

hollow mortar
hasty iron
#

yes?

#

use the context manager

#

with open(...) as file:

#

that will automatically close the file for you

hollow mortar
#

ohhhh okay thanks so i use this one it close it auto

#

but it wont read it now

upbeat otter
#

why is this not displaying the image?

hollow mortar
upbeat otter
#
embed = discord.Embed(title="Drake Hotline Bling", color=ctx.message.author.color)   embed.set_image(url="attachment://Drake Hotline Bling.jpg")
upbeat otter
stiff nexus
#
class Dropdown(discord.ui.Select):
    def __init__(self):

        options = [
            discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟄'),
            discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
            discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦')
        ]

        super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):

        await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')


class DropdownView(discord.ui.View):
    def __init__(self, ctx):
      
        super().__init__()
        self.ctx = ctx
        # Adds the dropdown to our view object.
        self.add_item(Dropdown())
    
    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message(
                embed=discord.Embed(description=f"{utily.error} Sorry, you can't use this! This interaction belongs to {self.ctx.author.mention}.",color=0xffffff), ephemeral=True)
            return False
        return True

    @commands.command()
    async def drop(self, ctx):
      await ctx.send('Pick your favourite colour:', view=DropdownView())
#
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/owner.py", line 208, in drop
    await ctx.send('Pick your favourite colour:', view=DropdownView())
TypeError: __init__() missing 1 required positional argument: 'ctx'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'ctx'
hasty iron
#

the error is pretty clear

#

you didnt pass in ctx to DropdownView()

upbeat otter
maiden fable
#

Any error?

upbeat otter
hollow mortar
maiden fable
#

Ah play

#

Okay*

unkempt canyonBOT
#

Hey @hollow mortar! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

waxen granite
upbeat otter
hollow mortar
#
@bot.event
async def on_message(message):
    f = open("badwords.txt" , "r")
    liness = f.read()
    if any(word for word in liness if message.content.lower() == word):
        await message.delete()
        await message.channel.send("You Cant Say That")
    await bot.process_commands(message)```
hollow mortar
upbeat otter
#

i tried using txt files to store words too, it wont work

hollow mortar
#

no it work

upbeat otter
hollow mortar
#

but the only problem with me is my old code it only remove words when you type it single without anything with them

#

look any try by your self

hollow mortar
#
@bot.event
async def on_message(message):
    f = open("badwords.txt" , "r")
    liness = f.read()
    if message.content.lower() in liness:
        await message.delete()
        await message.channel.send("You Cant Say That")
    await bot.process_commands(message)

#

this one work but like this

slate swan
#

so basically im making a discord bot that will say random shit like "cheese dick" and i have everything setup but idk what to put here:
await message.channel.send("")

hollow mortar
#

lets say mom word in one of the badwords line if you type youur mom it doesnt get deleted it only delete when type mom

upbeat otter
hasty iron
# waxen granite can u give an example? i am not able to do it

i explained pretty clearly, have 2 lists, when iterating through diff check if value is True, if it is append param to the first list and if it is false append param to the second list, after the for loop you're going to add two fields which are the removed and added permissions, lets take the first list being the added and the second list being the removed ones, you're going to do embed.add_field(name="Added Permission(s):", value=", ".join(first_list), inline=False) and embed.add_field(name="Removed Permission(s):", value=", ".join(second_list), inline=False)

slate swan
#

`import discord
import os
import random

with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))

print(random.choice(words)) 

with open("fade.txt", "r") as file:
data = file.read()
words = data.split()

word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])

client = discord.Client()

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

@client.event

async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('hi'):
  await message.channel.send("")

client.run(os.environ['TOKEN'])`

hollow mortar
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.

upbeat otter
slate swan
#
import os
import random

with open("fade.txt", "r") as file:
    allText = file.read()
    words = list(map(str, allText.split()))

    print(random.choice(words)) 

with open("fade.txt", "r") as file:
    data = file.read()
    words = data.split()

    word_pos = random.randint(0, len(words)-1)
    print("Position:", word_pos)
    print("Word at position:", words[word_pos])

client = discord.Client()



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



  @client.event


  async def on_message(message):
    if message.author == client.user:
      return



    if message.content.startswith('hi'):
      await message.channel.send("")


client.run(os.environ['TOKEN'])```
hollow mortar
#

it give you the words in badwords.txt

upbeat otter
#

any extra spaces?

hollow mortar
#

line by line

#

mom
love
hate
fuck

#

like this

upbeat otter
#

try using message.channe.purge once

#

also

#

@hollow mortar split the words to make a list too

hollow mortar
#

i didnt understand anything from you

upbeat otter
hollow mortar
upbeat otter
#

then try to use string comprehension

upbeat otter
hollow mortar
#

i cant use it like line by line every word ?

#

and im not good at lists and that shit

waxen granite
# hasty iron i explained pretty clearly, have 2 lists, when iterating through `diff` check if...
        list1 = []
        list2 = []
        if before.permissions != after.permissions:
            diff = set(after.permissions).difference(set(before.permissions))
            for perm, value in diff:
                if value == True:
                    list1.append(perm)
                    embed.add_field(name = "Added Permission(s):", value ='\n'.join(list1), inline =  False)
                else:
                    list2.append(perm)
                    embed.add_field(name = "Removed Permission(s):", value ='\n'.join(list2), inline  = False)
                await logChannel.send(embed = embed)``` is this correct?
upbeat otter
hollow mortar
hasty iron
upbeat otter
#

dm me

hasty iron
#

i said after the for loop add them

waxen granite
# hasty iron i said after the for loop add them
        list1 = []
        list2 = []
        if before.permissions != after.permissions:
            diff = set(after.permissions).difference(set(before.permissions))
            for perm, value in diff:
                if value == True:
                    list1.append(perm)                    
                else:
                    list2.append(perm)
                embed.add_field(name = "Added Permission(s):", value ='\n'.join(list1), inline =  False)
                embed.add_field(name = "Removed Permission(s):", value ='\n'.join(list2), inline  = False)    
                await logChannel.send(embed = embed)```
hasty iron
#

you are still adding them inside the for-loop

#

i said after it

waxen granite
#

ok sorry :#

#

works thanks

#

but

#

when i only add perm or only remove perms it doesnt work

stiff nexus
#

i did

    async def on_timeout(self) -> None:
        self.children[0].disabled = True

        self.children[0].label = 'Closed'
        await self.message.edit(view=self)
``` it did not work
upbeat otter
#

why isnt this displaying the image 🄲

embed = discord.Embed(title="Drake Hotline Bling", color=ctx.message.author.color)
embed.set_image(url="attachment://Drake Hotline Bling.jpg")
waxen granite
#

since there is no value for other field @hasty iron

stiff nexus
slate swan
#

im trying to make a bot that says either of these things but its saying all of the phrases

#

i already did set it up so it would be random but its not saying the random words

#
import os
import random

with open("fade.txt", "r") as file:
    allText = file.read()
    words = list(map(str, allText.split()))

    print(random.choice(words)) 

with open("fade.txt", "r") as file:
    data = file.read()
    words = data.split()

    word_pos = random.randint(0, len(words)-1)
    print("Position:", word_pos)
    print("Word at position:", words[word_pos])

client = discord.Client()



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



  @client.event


  async def on_message(message):
    if message.author == client.user:
      return



    if message.content.startswith('hi'):
      await message.channel.send(words)


client.run(os.environ['TOKEN'])```
maiden fable
#

await message.channel.send(", ".join(words))

slate swan
#

its just doing this now

#

same thing but without the brackets and quotes

maiden fable
#

Yea

stiff nexus
#
    async def on_timeout(self) -> None:
        self.children[0].disabled = True
        self.children[0].label = 'Closed'
        await self.message.edit(view=self)
```its not disabling the dropdown
maiden fable
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3.10/library/exceptions.html#IndexError "IndexError").
gloomy quest
#

Hi

slate swan
gloomy quest
#

How to make command classes

waxen granite
#

where is random.choice(words) like you claim in your code?

agile goblet
#

thatll just print it

waxen granite
#

and what do you want to do?

agile goblet
#

make it a variable or put it in your send method

waxen granite
#

then do it as await ctx.send(random.choice(words))

#

or word = random.choice(words)

#

await ctx.send(word)

stiff nexus
#
    async def on_timeout(self) -> None:
        self.children[0].disabled = True
        self.children[0].label = 'Closed'
        await self.message.edit(view=self)
```its not disabling the dropdown
half briar
#

Hey

slate swan
#

if u did that, just await message.channel.send(word)

#

plus there is an extra ) at the end of your code

half briar
#

@bot.command()
async def tts(ctx,*, text:str):
    global gTTS
    language = "es-us"
    user = ctx.author
    speech = gTTS(text=text,lang=language,slow=False)
    speech.save("audio.mp3")
    channel = user.voice.channel
    print(channel)
    vc = await channel.connect()
    print(vc)
    sc = discord.FFmpegPCMAudio("audio.mp3")
    voi = vc.play(sc)
    voi.start()``````
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
How to fix?
slate swan
#

just fix your indentation

half briar
#

@slate swan

#

I try

#

But not fixed

slate swan
#

show code

#

Did u installed ffmpeg?

half briar
#

@bot.command()
async def tts(ctx,*, text:str):
    global gTTS
    language = "es-us"
    user = ctx.author
    speech = gTTS(text=text,lang=language,slow=False)
    speech.save("audio.mp3")
    channel = user.voice.channel
    print(channel)
    vc = await channel.connect()
    print(vc)
    sc = discord.FFmpegPCMAudio("audio.mp3")
    voi = vc.play(sc)
    voi.start()```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
How to fix?@slate swan
slate swan
#

this should work fine maybe

import discord
import os
import random


with open("fade.txt", "r") as file:
    allText = file.read()
    words = list(map(str, allText.split()))

    print(random.choice(words)) 

with open("fade.txt", "r") as file:
    data = file.read()
    words = data.split()

    word_pos = random.randint(0, len(words)-1)
    print("Position:", word_pos)
    print("Word at position:", words[word_pos])

client = discord.Client()



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



@client.event


  async def on_message(message):
    if message.author == client.user:
      return

word  =  random.choice(words)

if message.content.startswith('hi'):
    await message.channel.send(words)


client.run(os.environ['TOKEN'])
half briar
#

@slate swan py from discord import FFmpegPCMAudio

half briar
#

i tried

slate swan
#

Pip ?

half briar
#

Yes

slate swan
#

Pip install ffmpeg-python

#

but i dont think that code is working

half briar
#

@slate swan i installed

#

But still error

#

@slate swan ?

reef shell
#

Indentation *

hollow mortar
#
@bot.event
async def on_message(message):
    counter = 0
    with open("spam.txt","r+") as file:
        for lines in file:
            if lines.strip("/n") == str(message.author.id):
                counter+=1
        file.writelines(f"{str(message.author.id)}/n")
        if counter > 5:
            await message.guild
            await message.author.add_role(##id of my role )```
slate swan
hollow mortar
#

i have this code i dont think it will work cuz the await message.author.add_role

#

and help

slate swan
#
import discord
import os
import random

with open("fade.txt", "r") as file:
    allText = file.read()
    words = list(map(str, allText.split()))

    print(random.choice(words)) 

with open("fade.txt", "r") as file:
    data = file.read()
    words = data.split()

    word_pos = random.randint(0, len(words)-1)
    print("Position:", word_pos)
    print("Word at position:", words[word_pos])

client = discord.Client()

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

@client.event
async def on_message(message):
    if message.author == client.user:
      return
    elif message.content.startswith('hi'):
        word  =  random.choice(words)
        await message.channel.send(word)

client.run(os.environ['TOKEN'])

try this maybe, plus u should learn basic python before attempting to make a bot

#

nice

#

dope

hollow mortar
#

hey any idea how to fix this problem and if it can be fixed

#

i have 2 on_message events

#

the bot can make the both work only 1 that can work

#

any idea how to make them both work ?

hollow mortar
#

okai thanks alot

slate swan
#

np

proven elm
#

please learn basic python before asking hundreds of simple questions

steep estuary
#

pls tell me i forgot when i am calling a function it is giving some function codes i want to take the prefix which im returning

proven elm
steep estuary
#

load prefix is a func

proven elm
#

if youre trying to use a function then you need () after the name

steep estuary
jade jolt
#

is this in a command?

proven elm
#

it'd be load_prefix()

steep estuary
#

this the func return

#

i want the return

half briar
#

How to install ffmpeg in phone

steep estuary
jade jolt
steep estuary
#

no

jade jolt
#

then where

steep estuary
jade jolt
#

you can put help above async def

steep estuary
#

yes

jade jolt
#
@bot.command()
""" Help String """
async def c(ctx):
    # lol
steep estuary
#

but i did this belo every command

#

hmm

quiet coral
#

hello guys I know how to send DM with events can someone tell me how to send it with commands?

steep estuary
#

ctx.author.send()

quiet coral
#

thnnk you

steep estuary
#

someone help me

#

load_prefix is a function

#

and it is showing this

slate swan
#

u need to call it

steep estuary
#

how to show what the function is returning?

slate swan
#

load_prefix()

steep estuary
slate swan
#

this will call the function

steep estuary
#

hmm ok

#

let me try

pliant gulch
#

Confused to as how you will even pass the message parameter for your function

#

As where it is has no access to one

steep estuary
#

?

steep estuary
pliant gulch
#

Your function clearly shows two parameters

steep estuary
#

but now i can pass parameters

pliant gulch
#

Bot and message

steep estuary
#

yes and i cannot pass them

pliant gulch
#

Where do you get message here???

#

That's what I'm saying lol

steep estuary
#

so what should i do :/

#

i cannot convert this ??

#

<function load_prefix at that integer>

high flame
steep estuary
#

to what the function is returning

steep estuary
high flame
#

load_prefix(ctx.message) for example

#

it takes a message argument

pliant gulch
#

Your thinking about this wrong, if you think about it the help command gets fired with the prefix used

#

There you would set the prefix message

high flame
#

oh wait, a Bot arg as well

steep estuary
steep estuary
high flame
#

bot.command_prefix(message)

steep estuary
#

is there any way to get a prefix of bot in different servers?

high flame
#

yes that's what im saying

orchid talon
#

On_member_join command is not working why ?

steep estuary
high flame
slate swan
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.

orchid talon
slate swan
#

did u enable them?

steep estuary
high flame
orchid talon
#

Hmm

steep estuary
#

so i trying to make custom prefix

steep estuary
#

this is outside a command

orchid talon
steep estuary
slate swan
#

why not send it in text instead of screenshot

steep estuary
#

and this

high flame
#

you must have a discord.Message

steep estuary
steep estuary
high flame
#

you better do that inside the command so you'd use ctx.message

steep estuary
#

hmm

#

what if i get the guild id in on_ready

#

it will give guild id?

#

of each servers?

orchid talon
slate swan
# steep estuary

um seems like it's your function for command_prefix
It can not be asynchronous.

steep estuary
#

like

guild_ids = {}
@bot.event
async def on_ready()
  guild_ids[message.guild.id] = "prefix" 
```??
steep estuary
high flame
#

message isn't defined

steep estuary
#

hmm

orchid talon
high flame
#

you can cache prefix in json btw

steep estuary
orchid talon
#

K

high flame
#

in the get_prefix

#

if the server isn't cached

steep estuary
high flame
#

cached_prefixes is a dict you'll make

steep estuary
#

lol

#

oo

high flame
#

are you okay

steep estuary
#

everything is fine in prefix

#

but i have a command

slate swan
#

hi

steep estuary
#

this much is only related with it :/

high flame
#

...

steep estuary
#

i heard some where that we can change <function load_prefix at 0x0000029B7F9DE3A0>

slate swan
#

so i have a discord music bot which i am hosting at heroku but in the logs it says "no such file directory" the name of the file is correct

steep estuary
#

can we ?

slate swan
#

do I need to upload the mp3 file in github?

#

its not a "simple music bot"

slate swan
#

yes

steep estuary
#

aaaaaaaaaaaaa

slate swan
neon cradle
#

how do you send a file through a discord reply from button click

steep estuary
#

:/

neon cradle
#

TypeError: reply() got an unexpected keyword argument 'file'
can I really not send a file through replies

slate swan
#

Do i need to make a sep folder with song files so that the repo be cleaned?

neon cradle
#
@buttons.click
async def first_but(ctx):
    A = Scholarship()
    A.get_site_info(A.ordered_scholarship_set_3x5[2][2])
    for _ in range(3):
        await ctx.reply(file=discord.File(f"{_ + 1}.png"))
slate swan
#

what library is that?

neon cradle
#
@bot.command(name='asd')
async def name(ctx) -> None:
    await buttons.send(
        content="something here", channel = ctx.channel.id, components = [
            ActionRow([
                Button(
                    style = ButtonType().Primary,
                    label = "asdasdasd",
                    custom_id = "first_but",
                    emoji = {"name": "mage",
                             "id": "625891304081063986"
                        }
                ),
slate swan
#

will it work? because in pycharm i did the same by making a sep sound folder but the it showed no such file or directory

slate swan
#

I put the folder in the project folder

#

along with ffmpeg.exe files and the other venv

#

oh like
C:/desktop/bot/sounds

jade jolt
#

show the cwd listing

slate swan
#

C:\Users\Admin\Desktop\sauceyy

slate swan
jade jolt
#

current working directory

slate swan
#

there are the codes

@bot.command()
async def test(ctx: commands.Context):
    voice_channel: discord.VoiceChannel = ctx.author.voice.channel
    print(voice_channel.name)
    vc = await voice_channel.connect()
    vc.play(discord.FFmpegPCMAudio("cumming.mp3"))
    while vc.is_playing():
      time.sleep(.1)
    await vc.disconnect()
    await ctx.send('blah')
#

oh

#

so i put it in the mid of the codes?

#

yes

#

alr

steep estuary
#

pls help i just want a value on calling a function :/

slate swan
#

thank you so much

hasty iron
#

that will block the whole bot

#

time.sleep is blocking

#

use asyncio.sleep

#

or you could use a Future, and set_result in the after argument

brazen seal
#

someone can help me ?

steep estuary
#

why it is giving me <Record prefix='!'>
in postgres

hasty iron
#

do current_prefix['prefix']

#

and why are you using globals?

steep estuary
hasty iron
#

what?

#

why are global-ing server_prefix

steep estuary
#

i just want to get the servers prefix

hasty iron
#

you dont need global when something is outside your function

#

??? what??

#

you use fetchrow or whatever for that, not globals

slate swan
#

ping = await collection.find_one({'user_id': str(), 'reaction': str()}) Lets say thats a certain line to check if its in the db I need to able to check for the user_id in the message.content and then get the reaction which is stored in the same document
Considering this is a example of a document
Image
So I need to able to have something in user_id: str(xyz) and something in reaction: str(xyz)

steep estuary
#

i have a command which show help of commands

orchid talon
steep estuary
orchid talon
#

Hmm

hasty iron
#

!d discord.ext.commands.Context.prefix

unkempt canyonBOT
steep estuary
hasty iron
#

what..

steep estuary
#

how to use that?

hasty iron
#

im talking about that mod help string or whatever

#

mute*

steep estuary
#

let me explain u properlly :/

#

i have this function

hasty iron
#

ok so why are you doing f'{load_prefix}...'

steep estuary
#

and this variables below every commands

hasty iron
#

that wont send the prefix

#

it will send the repr of the function

#

thats why i said to use ctx.prefix

#

since you wont have to call anything

high flame
#

better discord šŸ‘€

magic stump
#

no

#

no šŸ™‚

#

Why bot send offline if i have status online? py @bot.command() async def test(ctx): await ctx.send(ctx.author.status)

high flame
#

LMAO

fallow mauve
#

how do i get the bot to test whether or not someone has reacted to it's message?

magic stump
hasty iron
#

Message.reactions?

fallow mauve
#

ok

#

so if i say

fallow mauve
#

with this bot if you use a command it shows a reaction below its message, and if you click it it deletes the message

#

how does that work?

fallow mauve
slate swan
#

hey so ik i am asking this after 20 mins

#

but the file directory is it has to be the one in pc or github?

hasty iron
#

why does it matter

#

what does github effect

slate swan
hasty iron
#

and what does github have to do with that?

barren bluff
#

Hi, can I ask how do I make the code so that my discord bot doesn't delete 14-day-old messages?

slate swan
#

i have almost like 30 sound files i want them to be organized thats why i put the sound files in a folder named sounds so according to zimblox he said to put r'file directory' so i have to put the directory of the project folder of my pc or github?

#

because when i put the directory of github bot joins and leave

hasty iron
#

i dont get why are you putting github into your sentences

#

what does github do to you?

slate swan
#

have you use heroku? or heard about it

hasty iron
#

i have

slate swan
#

yes

hasty iron
#

and its bad for discord bots

slate swan
#

so you have to connect github with heroku

slate swan
#

and i will see if any problems arise in future

hasty iron
#

dont use it

slate swan
#

why?

hasty iron
#
  • Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

  • Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

  • Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

  • Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

  • Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.

flat solstice
#

So I have this command which is giving me two errors.```py
@commands.command(description = "Lets users locate a specfic suggestion via it's message ID or link.", usage = "sug <[messsage link|ID] | [phrase]>", aliases = ["find", "find-sug", "search", "search-sug"])
async def test_sug(self, ctx, search: Union[discord.Message, str]):
suggestions = self.bot.get_channel(id = self.suggestions)
if search is discord.Message:
await ctx.reply(embed = search.embeds[0].copy(),)
else:
with ctx.typing():
matches = 0
output = " "
messages = await suggestions.history(limit = None, before = None, after = None, around = None, oldest_first = None).flatten()
for message in messages:
if search in message.embeds[0].description:
matches += 1
output = (output + f"{message.embeds[0].title()}")

            embed = Embed(title = f"I found `{matches}` suggestions matching `{search}`.", description = output)
            await ctx.reply(embed = embed)```I am getting the following error if I provide a msg link```py

ERROR:cogs.error_handler:TypeError: 'in <string>' requires string as left operand, not Message (In test_sug)
Traceback:
File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/modmail/cogs/some_commands.py", line 24, in test_sug
if search in message.embeds[0].description:and this error if i provide a phrasepy
ERROR:cogs.error_handler:IndexError: list index out of range (In test_sug)
Traceback:
File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/modmail/cogs/some_commands.py", line 24, in test_sug
if search in message.embeds[0].description:```

hasty iron
#

if search is discord.Message: this wont work

#

!e ```py
class Obj:
pass

obj = Obj()
print(obj is Obj)

unkempt canyonBOT
#

@hasty iron :white_check_mark: Your eval job has completed with return code 0.

False
flat solstice
hasty iron
#

that isnt right either

#

!d isinstance

unkempt canyonBOT
#

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

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

or you could do if type(obj) is class:

flat solstice
hasty iron
#

yes

hasty iron
#

and also this if search in message.embeds[0].description, search is a Message object and description is a string, ofc this wouldnt work

flat solstice
magic stump
magic stump
river kindle
#

Hi guys, I have a problem, I want that when a command is invoked the bot sends in a special channel which command the user used.
I did the command, except that with client get channel does not someone know how to help me?

here the code: @ client.command () async def slowmode (ctx, seconds: int): await ctx.channel.edit (slowmode_delay = seconds) await ctx.send (f "I have set the slowmode in this channel for {seconds} seconds!") await ctx.send (f "Command log <@ {ctx.author.mention}> used the slowmode command in <# {ctx.channel.id}> ") channel = client.get_channel (mychannel)

magic stump
#
@bot.command()
async def test(ctx):
    await ctx.send(ctx.author.status)``` Bot send offline why? 
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="g!", help_command = None,  intents=intents)
high flame
#

because

#

you don't have presence intents

lavish zephyr
#

does anyone knows where i can learn discord py with some examples?

high flame
#

do intents = discord.Intents.all() to enable them all

lavish zephyr
#

i'm reading it but i cant understands exactly what it is

#

for example, when_mentioned()

high flame
#

you'd need python knowledge to understand it

lavish zephyr
#

i know its when_mentioned(bot, msg)

#

but dont know how to make it respond

high flame
#

there's on_command(ctx) event

#

and on_command_completion if no errors in the command

high flame
river kindle
#

I want that when a user uses a command it causes a log in a specific channel of what he did, but as already said client get channel does not go

high flame
high flame
river kindle
#

what's the problem

dry copper
#

I am making a chat bot and a server utility bot
I wanna know how to keep it online 24Ɨ7

fallow mauve
#
@bot.command('help')
async def help(ctx=None, message=None):
  embed = discord.Embed(
        title='Help Menu:',
        description=('This is the help menu, where you can see the list of commands the bot can use.'), colour=0x1fc2ff)
  embed.add_field(name="__**Fun Commands:**__", value="** **", inline=False)
  embed.add_field(name=";diceroll", value="** **", inline=True)
  embed.add_field(name=";ping", value="** **", inline=True)
  embed.add_field(name=";coinflip", value="** **", inline=True)
  embed.add_field(name=";8ball [question]", value="** **", inline=True)
  await ctx.send(embed=embed)

why wont this command work?

high flame
river kindle
#

lemme try

high flame
#

that's the only way

dim cedar
#

anyone there?

high flame
#

don't use repl.it or a service that uses shared ips devices

dim cedar
#

i need help in making a leave a message cmd in my bot

dim cedar
high flame
#

buy

#

computers aren't free

fallow mauve
#

i saw that

high flame
#

lmao too

dry copper
#

Btw

fallow mauve
high flame
dim cedar
dry copper
#

Hmm

dim cedar
high flame
#

then?

dim cedar
dim cedar
high flame
#

:/

dim cedar
#

i need help in making a leave a message cmd in my bot

fallow mauve
#

leave message command, whats that?

river kindle
fallow mauve
high flame
fallow mauve
#

no error pops up when i run the command, no red line under the code, nothing

river kindle
fallow mauve
#

*that

high flame
#

error?

river kindle
# high flame how it doesn't work

if I enter the channel, and I try to use a command in another channel the bot sends. the message in the channel in which I ran the command and not in the one requested by me

dim cedar
high flame
fallow mauve
high flame
#

maybe you used ctx.send instead of TextChannel.send

river kindle