#discord-bots

1 messages · Page 440 of 1

slate swan
#

Sure

hallow wigeon
#

you are looping through guilds

#

you have to loop through text channels

slate swan
#

for guild in bot.guilds:
for channel in guild:

clever wind
#
import discord
from discord.ext import commands
import json
import os

client = commands.Bot(command_prefix = "=")

@client.event
async def on_ready():
  print("Ready!")

@client.command(pass_context=True)
async def register(ctx, member: discord.Member, *, nick):
    if member.id == ctx.author.id:
        await member.edit(nick='[0] ' + nick)
        await ctx.send(f'You have registered as {member.mention} ')
        #how to add roles?
        role = discord.utils.get(client.get_guild(ctx.guild.id).roles, id = 882783428406284308)
        await member.add_roles(role)
    if member.id != ctx.author.id:
        await ctx.send(f' Only register yourself!')

@client.command(pass_context=True)
async def ping_4v4(ctx, user: discord.Member):
  role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
  if role in user.roles:
        #if user has 4v4 host role, send embed
    await ctx.send(f" 4v4 ping hehe ")
  else:
    await ctx.send(f" You don't have perms! ")


    

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

whats wrong with this code

hallow wigeon
#

afkaik guilds don't have .send method

pure reef
#

there's like a rule for that

slate swan
#

U tell me

#

is there an error?

hallow wigeon
pure reef
#

@clever wind it's like a rule to not just ask what's wrong

clever wind
#

yeah im gonna send that

slate swan
#

There is no way he coded that

vale pendant
#

We need more information to help out.

clever wind
#

msg was too long

hallow wigeon
#

just send the main error line

clever wind
#
Ignoring exception in command register:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 15, in register
    await member.edit(nick='[0] ' + nick)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 681, in edit
    await http.edit_member(guild_id, self.id, reason=reason, **payload)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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/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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
pure reef
hallow wigeon
#

just read the error

pure reef
#

your bot don't got perms

hallow wigeon
slate swan
#

IM DINE

#

OH MY GOD

hallow wigeon
#

lol

slate swan
pure reef
#

😭😭

clever wind
#

goddammit didnt see that

slate swan
#

What does it say @hallow wigeon

pure reef
#

might be most simple error to fix besides indent nd unindent

slate swan
#

not a trick question

hallow wigeon
vale pendant
slate swan
#

Now think.

clever wind
#

also im learning man lol chill its a combination of stackoverflow and tutorials

slate swan
#

Think about how to fix a bot that is missing perms.

hallow wigeon
#

What?

pure reef
#

your bot possibly doesn't have admin 😶‍🌫️😶‍🌫️

hallow wigeon
vale pendant
slate swan
#

Oops

hallow wigeon
#

lol

slate swan
#

8

kindred epoch
#

No

vale pendant
#

Give it the perms it needs, not admin.

pure reef
#

not any bot

#

yeww can give your bot wtv

slate swan
#

Sussy backa

hallow wigeon
#

yea for test server give it admin

slate swan
#

yes?

pure reef
#

i'd rather add it with admin then have to test every cmd to see what permissions i have to give it

vale pendant
#

How can we help?

pure reef
#

nvm i jus remember yeww can choice in dev portal

hallow wigeon
#

this won't work

vale pendant
#

It will loop.

clever wind
#

it does work

hallow wigeon
#

what do you want

slate swan
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
hallow wigeon
vale pendant
#

@slate swan what are you trying to do?

pure reef
#

i asked if he wanted a certain channel or to send to a user he said any channels

slate swan
#

in one channel?

pure reef
#

.

slate swan
#

you must define the channels first

#

you can make a list, you can select a channel using string like (general,welcome etc)

hallow wigeon
#

I mean you can choose a random channel from guild.channels

pure reef
#

i do not code anymore soo

hallow wigeon
#

random.choice(guild.channels)

#

or just the 1st channel if you want too

pure reef
#

that's so ughhh

hallow wigeon
#

guild.channels[0]

kindred epoch
#

You can search for a channel named General and send it there

#

Add a try expect tho

vale pendant
#

I'd say get the first channel that's a text channel.

hallow wigeon
#

have different checks

kindred epoch
#

That's why I said add a try expect

pure reef
#

it's like discord.utilts.get(guild.channels

#

wowwww i'm rusty 😭😭

hallow wigeon
#

you can do like, if no general found, search for chat, if chat not found rest

vale pendant
#

Some servers has special fonts for chat or general.

hallow wigeon
#

for them you can have a check to send to random or 1st channel

pure reef
#

just create a channel for it .. but when i do that i have the problem of it cuz when it creates the channel for other servers it sends to them also

slate swan
hallow wigeon
#

and break if correct one found

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
    try:
        async with aiohttp.get(search) as r:
            result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await bot.say("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await bot.say("Your search terms gave no results.")
    except:
        await bot.say("Error.")``` could someone help me fix this? im new with apis and im experimenting with this, im not using any cogs either just as a note
slate swan
#

Didn’t think of that at all. Fair play

hallow wigeon
vale pendant
#

@slate swan Here I made one rq and this works:

@client.event
async def on_guild_join(guild):
    for channel in guild.channels:
        if channel.permissions_for(guild.me).send_messages:
            break

    await channel.send("etc")```
slate swan
# hallow wigeon ?

async with aiohttp.get(search) as r:
AttributeError: module 'aiohttp' has no attribute 'get'

hallow wigeon
#

you need a ClientSession

hallow wigeon
#

!d aiohttp.ClientSession

unkempt canyonBOT
#
class aiohttp.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, version=aiohttp.HttpVersion11, ...)```
The class for creating client sessions and making requests.
slate swan
#

import requests

#

i have

hallow wigeon
kindred epoch
slate swan
#

Fair

slate swan
hallow wigeon
hallow wigeon
slate swan
hallow wigeon
#

if I made a bot, i wouldn't even add that feature

vale pendant
hallow wigeon
kindred epoch
hallow wigeon
#

yea

slate swan
hallow wigeon
#
import aiohttp
 
ses = aiohttp.ClientSession()

async with ses.get("url") as res:
  # handle res
#

like here I named my session ses, so I did ses.get

#

I usually see a ClientSession as a browser

#

lol

vale pendant
#

Haha

#

There is going to be a error.

#

Change client to bot

#

Ahhh, okay.

#

Just making sure there is no errors.

hallow wigeon
#

add the check isinstance(channel, discord.TextChannel)

vale pendant
#

I think you can do if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):

hallow wigeon
#
@client.event
async def on_guild_join(guild):
    for channel in guild.channels:
        if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):
            break

    await channel.send("etc")
vale pendant
#

Yeah

hallow wigeon
#

indents are messed up in discord

pure totem
hallow wigeon
#

yea

#

but many forks

slate swan
#

yeah there are forks though

pure totem
#

So code doesn’t work

hallow wigeon
#

one of the famous forks is pycord

pure totem
#

Sorry what does forks mean

#

LOL

hallow wigeon
pure totem
pure totem
hallow wigeon
#

it will

#

but won't get updates

#

so like if you are making a new project, look for a fork

#

don't use dpy

pure totem
#

Oh hmm ok so py cord where are the docs

hallow wigeon
#

its I think .gg/pycord

#

we sent the updated if condition..

#

even after that not working

#

sus

slate swan
#

the channel.send needs to be where break is and you should get rid of the break

hallow wigeon
#

yea instead of break, have the send line

pure totem
hallow wigeon
#

kk

vale pendant
#

Hmmm, you don’t need intents right?

#

not indents,

#

Intents

#

What was the error?

#

hmm

#

aslong as it works

#

stops the for loop

#

i believe if all channels haev the permission it will send to all of them

#

since it's still in the for loop

kindred epoch
#

Yes it will

#

You can loop through them and after it sends you can break the loop

vale pendant
#

^

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
    try:
        async with aiohttp.get(search) as r:
            result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await ctx.send("Your search terms gave no results.")
    except:
        await ctx.send("Error.")```
any advice? theres an error on the aiohttp.get area im not sure what the error is exactly because of the handler at the end
pliant gulch
#

Just delete the try-except then and see the error you are suppressing

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
            async with aiohttp.get(search) as r:
            result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await ctx.send("Your search terms gave no results.")```
#

like that?

pliant gulch
#

obv don''t leave in indented

#

Dedent the parts inside of the try-except block

slate swan
#

edited, better?

pliant gulch
#

You didn't dedent it

vale pendant
#

Do what sasuke said, break it after you sent the message.

pliant gulch
#

dedent not indent which is what you just did

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
    async with aiohttp.get(search) as r:
    result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await ctx.send("Your search terms gave no results.")```
pliant gulch
#

Still not dedented, it should be at the same level

vale pendant
#

lmfao

slate swan
#

i havnt done this in years 😭

pliant gulch
#

Now it isn't indented correctly

vale pendant
#

Yeah

pliant gulch
#

The stuff inside of the context manager needs indentation

vale pendant
#

indent it

#

it should be at the same indent at await

#

if you don’t, it’s not gonna be in the if statement

slate swan
#

ok so the conext manager is the "await bit", correct?

pliant gulch
#

No the context manager part is the async with

#

Notice the :?

slate swan
#

yes

vale pendant
#

😂😂

#

no problem bro

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
        async with aiohttp.get(search) as r:
    result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await ctx.send("Your search terms gave no results.")```
better?
pliant gulch
#

No you indented the wrong part

vale pendant
#

💀

slate swan
#
@bot.command()
async def urban(ctx, *, search_terms : str):
    """Urban Dictionary search"""
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    search = "http://api.urbandictionary.com/v0/define?term=" + search_terms
    async with aiohttp.get(search) as r:
        result = await r.json()
        if result["list"] != []:
            definition = result['list'][0]['definition']
            example = result['list'][0]['example']
            await ctx.send("**Definition:** " + definition + "\n\n" + "**Example:** " + example )
        else:
            await ctx.send("Your search terms gave no results.")```
better?
pliant gulch
#

Yes

vale pendant
#

ily2 man

slate swan
pliant gulch
#

No it shouldn't as you said there was an error being suppressed

kindred epoch
#

No it will send the error

pliant gulch
#

This only shows the error

kindred epoch
#

Then send the error so we do less work finding out what's wrong

slate swan
# pliant gulch Yes

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'aiohttp' has no attribute 'get'

pliant gulch
#

get is a method of your ClientSession instance idk how I didn't notice that earlier

slate swan
#

whats that mean exactly

pliant gulch
#

Look at aiohttp docs, see this example on how to properly use it here

#

The relevant part is where the context manager starts

#

You don't need another async function as this is already in one

slate swan
#

so what do you recommend i put down

pliant gulch
#

Just look at their examples

#

Gives you exactly what you need

slate swan
#
async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://api.urbandictionary.com/v0/define?term=') as resp:
            print(resp.status)
            print(await resp.text())


loop = asyncio.get_event_loop()
loop.run_until_complete(main())```
#

like that?

slate swan
# pliant gulch Read
async with session.get('https://api.urbandictionary.com/v0/define?term=') as resp:
            print(resp.status)
            print(await resp.text())


loop = asyncio.get_event_loop()
loop.run_until_complete(main())```
gloomy coral
#

wht rlly?

pliant gulch
#

The loop parts get rid of, and change the url to your url

gloomy coral
#

How to stop playing audio with ffmpeg

pliant gulch
#

Keyword of what I said earlier, “example” use it as a reference idk why you are copy and pasting it

#

You literally had most of this code already just needed to swap a few parts out by referencing the example

clever wind
#
@client.event
async def on_member_join(member):
  guild = client.get_guild(870969337945669722)
  channel = client.get_channel(870969338235084841)
  await channel.send(f' Welcome to Hive 4v4s, {member.mention}! Have fun!' )
kindred epoch
#

Huh?

#

Vultr? Overprice?

clever wind
#

nvm the guild cuz ill use it later but it doesnt seems to work with no errors

gloomy coral
#

exactly

#

@kindred epoch , i have 60 bucks in credits

kindred epoch
#

Dam nice

gloomy coral
#

50 free, (Expires 2021-09-16)

#

and 10 paid

kindred epoch
#

Nice

gloomy coral
#

i want to buy a 5 dollar vps. How can i make the most out of it?

kindred epoch
#

Idk

gloomy coral
#

so that i use my free credit and all

gloomy coral
kindred epoch
#

5 dollars is to much

gloomy coral
#

wdym?

kindred epoch
#

3.50 works really fine for me

#

And it gives ipv4

gloomy coral
#

but on 5 dollars i cld run 2 bots right

gloomy coral
kindred epoch
#

Ig

#

2.50 does not give ipv4

gloomy coral
#

ok... im taking 5 anyways. My question is with the amount of credits i have, how can i maximise it

kindred epoch
#

If you use dbs then get the extra features

gloomy coral
#

dbs?

kindred epoch
#

Like backup and stuff like that

gloomy coral
#

databases?

#

oh.... no i dont want tht

kindred epoch
#

Ye

gloomy coral
#

i just want to get as much time as possible

#

i am a student, i can not pay for many months

slate swan
#

I'm using discord.py, I need help with something. I'm trying to make it so when a user runs a command, it gives them a prompt and then waits for more input. How do I achieve this without having to use if statements to determine if they used a command previously

#

nvrmind

gloomy coral
#

how can i stop ffmpeg playing audio?

#

and how to give an error if it is already playing

boreal ravine
#

Is it true discord takes 2 hours to register slash commands?

covert igloo
#

hey friends

#

I need help with this

#

if i want something to have 2 trigger words

#

would i just use "or"

gloomy coral
#

use aliases

covert igloo
#

explain please

#

i am a beginner

gloomy coral
#
@commands.command(aliases=['leave', 'disconnect'])
    async def shoo(self,ctx):```
covert igloo
#

this is what i had it as

#

but it kept triggering for every word instead of ch 4 and chapter 3

gloomy coral
#

ok

#
elif isinstance(error, discord.errors.ClientException):
            print("1")
            await ctx.send(embed=discord.Embed("Sorry im already playing audio. Do !stop to stop it",color=discord.Color.random()))```
#

This should handle it if it is already playing audio right?

clever wind
#
@client.event
async def on_member_join(member):
   channel = discord.utils.get (member.guild.channel, name='welcome')
   await channel.send(f' Welcome to the server, {member.mention}')

this doesn't work

gloomy coral
#

does it have intents?

slate swan
#
            try:
                rpl = await client.wait_for("message", timeout = 3.0, check=None)
                print(rpl.content)
            except TimeoutError:
                print("what")
#

hold on thats super messy

#
try:
  rpl = await client.wait_for("message", timeout = 3.0, check=None)
  print(rpl.content)
except TimeoutError:
  print("what")
#

ok so, does anyone know why when it's timing out, it still gives me an error rather than catching the exception

#

It still gives me TimeoutError

clever wind
#

i feel like im trying to code this in py before rewrite maybe thats why its not working

vale pendant
#

await ctx.send(random.choice(responses)

#

import random lib

clever wind
#

dont u have to get channel id or smth too?

#

idk

gloomy coral
#

except asyncio.TimeoutError:

slate swan
#

it says asyncio is not defined

#

I'm using "import discord"

gloomy coral
slate swan
#

you forgot a closing parentheses in a line above

gloomy coral
#

did you put bot.event?

slate swan
slate swan
#

@slate swan check to make sure you didn't forget a closing parentheses in any lines above, this is the most common cause for an error like this

gloomy coral
#

yes

clever wind
#

still doesnt work

gloomy coral
#

How can i make a random "tip" get sent every 100/200 commands in my discord bot?

gloomy coral
#

wht?

#

tht makes no sense

crisp pine
#

how do i add an image to this it keep giving error when i try

slate swan
#

OH

#

I misread that

#

Thought you wanted it to send a tip every certain amount of time

gloomy coral
#

lol

slate swan
#

Im too lazy to read that entire thing lmao

crisp pine
#

could

thumbnail=    'https://media.discordapp.net/attachments/867833997728022599/882442193669849088/ezgif-6-0daf8e1e9fd6.gif'```
#

@slate swan

slate swan
#

ok quick question tho, this is a bit off track. Why do python devs have a bad habit of using single quotes to encase strings lmao

restive river
#

quick follow-up question: why is it a bad habit

unkempt canyonBOT
#

Hey @slate swan!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

slate swan
restive river
#

python is also one of the only languages where indenting matters

slate swan
#

true lmao

restive river
#

but indenting is not therefore "bad practice"

#

i dunno for me it's just "a thing about python" that's kind of a weird quirk

#

I'll give you "Weird Quirk"

slate swan
#

lmao

crisp pine
#

here good?

restive river
#

code as an image is pretty inconvenient

slate swan
#

do discord servers have unique IDs so I can create a web server and store bot settings differently for multiple discord servers

restive river
#

in the code it's called a "guild"

#

but yeah totally has an ID

slate swan
#

ahh ok

restive river
#

like i have a bot that's on two servers and it very much needs to know guild ID because if it wakes up and has to send a message "channel ID" is not enough

#

gotta know both

#

especially if it's looking up the channel by name

#

turns out there are a lot of "#general"s out there

slate swan
#

yes lmao

restive river
#

also like, makes sense when you think of "big bots"

#

like there's a github bot out there, how many servers have installed that one

#

it's a large number

#

my stuff is for one or maybe two servers but

#

maybe one day i'll be famous

slate swan
#
@bot.command()
async def testurban(ctx):
    search_terms = search_terms.split(" ")
    search_terms = "+".join(search_terms)
    async with aiohttp.ClientSession() as session:
        request = await session.get('http://api.urbandictionary.com/v0/define?term=' + search_terms)
        catjson = await request.json()
    embed = discord.Embed(title="{search_terms}", color=0xf6dbd8)
    embed.add_field(name=f"Definition" + catjson['definition'])
    embed.add_field(name=f"Upvotes:", value=f":green_circle: " + catjson['thumbs_up'])
    embed.add_field(name=f"Downvotes:", value=f":red_circle: " + catjson['thumbs_down'])  
    await ctx.send(embed=embed)``` not sure where i went wrong
scarlet pond
slate swan
exotic patrol
fickle turret
slate swan
#

ill see if i even did that give me a min

#

Is it a discord TOS violation if I make it to where any server owner who has my bot has access to see when a user has been banned from other servers with the same bot and why

#

I feel like it's honestly just useful. Oh you wanna be mod, huh? lemme just pull up your collective record from servers who also use this bot

#

lmao

maiden fable
#

@slate swan I don't really think it will be a ToS violation but imho, it can be sort of a privacy thing cz I don't really think any server would want to leak it's ban list to other server owners...

slate swan
#

It's a feature. You can choose what info to upload

maiden fable
#

This way, raids can easily happen. Seeing the raiders are unbanned, chances of raids are increased imho

slate swan
#

Well I appreciate your honest feedback, man! I just finished learning python, so now is the point where I'm actually doing stuff

maiden fable
#

Ah, cool. Best of Luck with all that!

#

BTW @visual island disnake is in alpha testing now, in case you will want to install it from pip

visual island
#

@maiden fable you woke up at 10 again?

maiden fable
#

7408_shrekstare Kylee comes here before I could ping

maiden fable
slate swan
maiden fable
#

!pypi disnake

unkempt canyonBOT
maiden fable
visual island
#

o yeah

slate swan
#

I do have a really good idea though, basically it's a bot you can DM and set up a profile with stuff like your age range, interests and such and look for a random person to chat with

maiden fable
maiden fable
slate swan
#

lmao ikk. But I just wanna make something coool

#

Though it's a good idea

#

Oh I know! I'll make a program that shows me the location of all working mcdonalds ice cream machine- oh wait, the simpsons already did it bro

maiden fable
#

😂

slate swan
#

Make a discord bot Work at McDonalds

maiden fable
#

Lmao

slate swan
#

You might find this super cringey, but I started programming because of a certain 12 year old crackhead.. if you get the reference, we are now friends

maiden fable
#

Haha

visual island
maiden fable
#

For me, I always had an interest in programming. I wrote my first program at the age of 12?

maiden fable
slate swan
#

I was talking about Michael Reeves btw

#

_test_guilds ASWaitWhat

slate swan
#

disnake stores test guild

slate swan
maiden fable
# visual island

7408_shrekstare you install dpy from pip, but for bug fixes, you install from master branch

prisma wedge
#

!python praw

#

!pypi praw

unkempt canyonBOT
#

PRAW, an acronym for `Python Reddit API Wrapper`, is a python package that allows for simple access to reddit's API.

maiden fable
#

Or u can monkeypatch it if u want. It would be faster

slate swan
#

for bug fixes, you install from master branch
quote this

maiden fable
slate swan
#

rooThink oh yea I just did it

#

Install stable -> has bugs
Install from master -> stable

#

only disnake

maiden fable
#

Eh

vagrant brook
#

lmfao

maiden fable
#

I don't really think there is a reason to publish another reason to fix only one bug

#

I never said master was stable

#

it just has one or two extra bug fixes

#

Also, it's in Alpha testing, so you can't blame anyone haha

slate swan
#

What's a good format for a file to store data such as tables locally on my laptop for use of the discord server

maiden fable
#

Don't kill me

#

Anyways, use the discord message as db

#

That's what I do hehe

slate swan
#

wha-

#

are you fr

#

I don't trust disnake anymore notlikeblob

#

Rapptz/disnake

vagrant brook
#

😎

maiden fable
#

Lmao

#

Ah, I know why that's happening

slate swan
#

I was gonna try learning SQL but figured it's not worth the hassle for a simple discord bot

#

at least not rn

maiden fable
#

We just did Ctrl+D to exchange discord with disnake

maiden fable
slate swan
#

Sure

maiden fable
vagrant brook
#

bruh

#

That'd be inefficient

slate swan
#

bro wtf

maiden fable
maiden fable
vagrant brook
#

I mean your database

maiden fable
#

Ah

slate swan
# maiden fable

It might be first time I'm recommending someone to use json, please stop this blobpain

maiden fable
#

Well, it's abandoned now. It's a private bot anyways

slate swan
#

I once considered using the google sheets API for a database

maiden fable
slate swan
#

ok so quick question:

maiden fable
#

?

slate swan
#

I wanna store python arrays outside of the script, on like a txt file or something, can I do that

maiden fable
#

Mhm

slate swan
#

How would I go about doing that effectively

#

Database

maiden fable
#

Akshu will kill me if I say that u can use JSON to store list

slate swan
#

lmao

#

I'm already super confused about the discord message thingy

#

Exactly, but you can still use json with some efficiency tricks

maiden fable
#

He's already in shock that how can I use messages as db lmao

pliant gulch
#

I'm in shock on how you even thought about it and went through using discord channel as a database

slate swan
#

I won't wonder if he even uses pen-paper now notlikeblob

maiden fable
pliant gulch
#

Hmm I don't know I think I would prefer json over what you did since it would be easier to interface, etc

#

And you know, imagine if you had a dynamic prefix and the message wasn't cached

#

There goes all the commands

slate swan
#

It's not good to use json in bot but if you still want to do that, you can just create a timed task to asynchronously open the file every few minutes and dump the cache

#

im making my own file type because I am extra lmao

maiden fable
pliant gulch
#

You don't really need to dump the cache

#

You can read the JSON when constructing the bot, cache every data. On commands that update, update the cache

#

Then in your close method write to the database

maiden fable
#

Eh, it's a private bot anyways. I don't want to get ratelimited by using it in a big bot

slate swan
#

On the off-chance my bot were to blow up, so would my computer

#

rooThink I mean by storing in json instead of a database

pliant gulch
#

Yea, which is what I was talking about

slate swan
pliant gulch
#

If that is the case, use aiofiles and only open the file in the same method that writes any new data

slate swan
#

I wanna get a real web server, but it scares me after my friend telling me his heats up his entire room to 104 degrees F

#

Yeah

cobalt jacinth
#

how do i set local image in embed

pliant gulch
#

!local-file

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.

slate swan
#

This is my discord bot. He's an automatic mod system

#

(pfp and name is temporary)

maiden fable
#

Lmao

#

7408_shrekstare how do y'all get those good tags like 4600 and stuff.... I never got those :c

slate swan
#

I was just about to say that

#

A while ago my name was Retro_#6699 by accident

maiden fable
#

Ok?

slate swan
#

it was after my nitro expired so I got randomized again

maiden fable
#

No

#

I mean the bot tag lol

slate swan
#

yeah ik lol

#

just keep making new ones til you get a good number idk

maiden fable
#

😂

#

Tried that

#

Doesn't work

slate swan
#

Here's an idea:

#

Why don't nitro users also get to customize the tag for their bots

maiden fable
#

Indeed

#

But instead, discord wants to make slash commands popular by making messages intent a privileged intent

pliant gulch
#

Great, add another useless nitro feature rather then fix things for developers

maiden fable
#

Yikes. Soo many yikes 😬

slate swan
#

just out of curiosity, does anyone use pycord instead of discord.py

maiden fable
#

Nah

#

I gonna use disnake soon. So no pycord for me

slate swan
#

pycord is kind of trash

maiden fable
#

Idk

slate swan
#

I'm gonna make a server called "EA" and you have to buy credits for sending messages lmao

slate swan
#

ikr

#

[redacted]

#

that was stupid, ima shut up now

maiden fable
#

😂

#

Well, I went AFK

slate swan
#

A friendly kid

#

(AFK)

#

Hunter, add me as a friend?

ornate linden
#

is there any way a role can edit the role above it?

ornate linden
#

that makes my code a lot easier

slate swan
#

is there a library I can use to allow me to create folders on my computer with python

#

nvrmind, just found it

vagrant brook
#

That's builtin

#

import os

slate swan
#

yeah, that's the one I just found

#

tank u anyway

maiden fable
#

Missing Permission or something

ornate linden
#

yeah I know

maiden fable
#

Ah cool

ornate linden
#

god my code is getting increasingly messy and i dont know how to clean it

maiden fable
#

Uhh, follow PEP 8?

#

!pep 8

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

Active

Created

05-Jul-2001

Type

Process

ornate linden
#

oh nice didn't know that was a thing

maiden fable
#

Haha now u do

#

Also, use black or flake8

#

!pypi black

unkempt canyonBOT
maiden fable
#

!pypi flake8

unkempt canyonBOT
slate swan
#

when using the on_guild_join event, how do I find the channel the bot joined in on

slate swan
#

or like, uhhh

#

I wanna make it to where it will send a message when it joins a server, how do I find the best channel for that

maiden fable
#

What if no channel like that is set?

slate swan
#

oml lmao

vale pendant
#
@client.event
async def on_guild_join(guild):
    for channel in guild.channels:
        if channel.permissions_for(guild.me).send_messages and isinstance(channel, discord.TextChannel):
            break

    await channel.send("Thanks for inviting me!")
#

This will find the first channel the bot is allowed to send messages in.

maiden fable
#

Ah, so u mean, like Groovy does it?

vale pendant
#

Yeah i’m pretty sure that’s what he means.

maiden fable
#

Ah, I misunderstood then

vagrant brook
#

there's this one

vagrant brook
#

!d discord.Guild.system_channel

unkempt canyonBOT
#

system_channel```
Returns the guild’s channel used for system messages.

If no channel is set, then this returns `None`.
waxen granite
#

Can we kick more than 1 person at a time?

boreal ravine
#
    @commands.command()
    async def help(self, ctx):
      embed=discord.Embed('Full Help Page', description='hi')
      embed.add_field(name='Commands:', value='Hug: `hugs the user`\nBonk: `bonks the user`\nKiss: `kisses the user`\nSpank: `spanks the user`\nSlap: `slaps the user`')
      await ctx.send(embed=embed)
``` why isnt this working
brazen raft
boreal ravine
#

oh I didn't see it my bad

gloomy coral
#

how can i host my discord py bot? on vultr

slate swan
#

"rpl = wait_for("message", check = None, Timeout = 60.0)", telling me wait_for is not a function

waxen granite
#

Add the required buildpack

#

Add the language pack too

slate swan
#

or whatever you defined commands.Bot as

#

"commands" not found

#

Am I just dumb, ffs

slate swan
#

where's your bot constructor?

#

Oh it's Client.wait_for

#

yes, so you defined Client as commands.bot

#

constructor for what lmao

#

.. didn't you do something = commands.Bot(...)?

#

Or are you using discord Client

#

No, I just have client = discord.Client() lmao

#

I don't have a var for bot

#
@bot.command(pass_context=True)
async def hand(ctx):
    variable = [
         "1",
         "2"]
    embed = discord.Embed(color=0xf6dbd8)
    embed.set_image(url=variable)
    await ctx.send(embed=embed)``` command dosnt work, any ideas? the variables are supposed to be urls but i removed the urls to prevent spam
#

okay, hmm

#

try client.wait_for

#

Just did, figured it out

#

thx tho

slate swan
slate swan
#

try another variable random.choice(variable) and set this to the url

#
@bot.command(pass_context=True)
async def hand(ctx):
    variable = [
         "1",
         "2"]
    embed = discord.Embed(color=0xf6dbd8)
    embed.set_image(url=random.choice(variable))
    await ctx.send(embed=embed)```
#

helphhhhh

#

like that?

#

yeah try

slate swan
unkempt canyonBOT
slate swan
#

bot.guilds not servers

slate swan
#

thnx

crude skiff
#

does anyone knows about Py-cord

valid patio
#

i have a doubt how can i make a discord bot send a .txt

maiden fable
maiden fable
unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
valid patio
valid patio
# maiden fable !d discord.File

umm is this correct ? if message.content.startswith('!docEntity'): await message.channel.send.discord.File(fp, filename=Entitydoc*, spoiler=False)

#

anyone ?

maiden fable
unkempt canyonBOT
#

await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
maiden fable
#

Use the file kwarg

valid patio
#

ok

valid patio
maiden fable
#

Can I see where u have defined launch_time?

boreal ravine
#

OHHH my bad sorry

slate swan
#

pls help

#

me i want to mention a user

#

pls

spring flax
#

!d discord.Member.mention

unkempt canyonBOT
spring flax
#

@slate swan ^

slate swan
#

how

#

author.mention

#

?

spring flax
willow vine
#

hey i'm using replit to make a music bot, do i have to install the ffmpeg software on my system or can i just import the required libraries ?

visual island
#

hi, so in dpy you can do like class MyCog(commands.Cog, name="MyCog") right? how did they implement it? i've tried using __init_subclass__ and i think it doesn't work quite well, and raise an error: TypeError: __init_subclass__() takes no keyword arguments

#
class EnumMeta(type):
    """This metaclass makes a class iterable (iterate through class vars)."""
    def __iter__(self):
        yield from [i for i in self.__dict__.values() if str(i).isdigit()]

    def __init_subclass__(mcs, **kwargs):
        mcs.__type__ = kwargs.pop("type")


class Channels(metaclass=EnumMeta, type="hi"):
    ...
```code btw *changed a bit
slate swan
#

where to put the command

spring flax
#

why not use commands

#

you are using a on_message event to check for commands

#

when you can just make commands yourslelf

slate swan
slate swan
#

lolwhile learning

spring flax
#

all your bot features are with on_message event?

slate swan
#

sorry lol

spring flax
#

bruh

slate swan
spring flax
#

well, that is a bad practice

slate swan
#
@bot.event
async def on_message(message):
 mention = f'<@!{bot.user.id}>'
 if mention in message.content:
        embed=discord.Embed(title=f"Server Prefix", description=f"My prefix in this server is `{prefix}`", color=0x008000)
   
        await message.channel.send(embed=embed)

        await bot.process_commands(message) ```
when i add these the prefix is not working when i do `.help` it is not coming but when i remove this it is coming is there any problem with this?
slate swan
spring flax
#

how would you even have args for commands lol

spring flax
#

or what do you want?

#

You want to mention who used the message? do message.author.mention

#

I would suggest you use commands instead of the on_message event, but it seems you've gone far already

#

but you can still do it

slate swan
slate swan
lament mesa
spring flax
#

@slate swan yes do what i sent

#

message.author.mention

visual island
slate swan
slate swan
spring flax
#

Oh

spring flax
#

What are you trying to do @slate swan

slate swan
spring flax
#

Try this:

slate swan
#

k

spring flax
#
await message.reply(embed=embed)```
slate swan
visual island
limber mountain
limber mountain
#

no this is python

#

dude talking about the error dude

slate swan
lament mesa
# visual island ```py class EnumMeta(type): """This metaclass makes a class iterable (iterat...

!e ```py
class EnumMeta(type):
"""This metaclass makes a class iterable (iterate through class vars)."""
def new(cls, name, bases, attrs, **kwargs):
attrs['type'] = kwargs.get('type', None)
return super().new(cls, name, bases, attrs)

def __iter__(self):
    yield from [i for i in self.__dict__.values() if str(i).isdigit()]

class Channels(metaclass=EnumMeta, type="hi"):
...
print(Channels.type)

unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

hi
limber mountain
slate swan
slate swan
slate swan
lament mesa
boreal ravine
#

@slate swan why no make commands and not on messages?

visual island
lament mesa
#

super what?, the __new__?

visual island
#

yeah

lament mesa
#

yes

boreal ravine
visual island
slate swan
#

and I dont know how do i

boreal ravine
slate swan
#

i need someone to help me edit

#

or else i will have to use on_messgae

#

on_message

#

@boreal ravine

lament mesa
# visual island why

__new__ must return the newly created class, type.__new__(cls, name, bases, attrs) returns the class according to the given attributes, because you are overriding the __new__ you need to return the newly created class

solar quiver
#

Anybody with experience of Discord Bot development?
I have Work for you!

visual island
#

wait

#

it still returns None

boreal ravine
crystal grove
#

How do you save a sent screenshot as a temp photo , like png

visual island
lament mesa
#

havent found a use for it other than that

visual island
#

but metaclasses are fun imo

limber mountain
visual island
limber mountain
#

guys can we do the module exports things in python can yall teach me

#

@visual island

slate swan
#
@commands.has_permissions(kick_members=True)
async def kick(ctx, *, member:discord.User, reason="No reason provided"):
    if member == None or member == ctx.message.author:
        await ctx.channel.send("You cannot kick yourself.")
    if bot.role.position > member.top_role.position:
        await ctx.send("You cannot do this action on this user due to role hierarchy.")    
        return
    await ctx.guild.kick(member, reason=reason)
    await ctx.send(f"Kicked **{member}**")
    await member.send(f"You have been kicked from **{ctx.guild}** for Reason: {reason} Responsible Moderator: **{ctx.author}**")
    return

whats wrong in this if i try to ban a member above bots role it is not send you cannot do this action due to role hierrachy

heavy folio
#

how do i get user's status? i mean i know how but i also have an emoji for each status, how do i send the emoji with their status name

half wind
#

can anyone recommend a good discord bot's code here?

slate swan
slate swan
slate swan
boreal ravine
boreal ravine
slate swan
boreal ravine
slate swan
#

let call

#

or dm

boreal ravine
#

yes DMs

slate swan
#

me lol

slate swan
#

it'll return a emoji if there is

#

str(member.status) returns without emoji

heavy folio
#

oh

#

wait wdym

#

mine doesnt show an emoji

limber mountain
#
in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type set is not JSON serializable
``` what is wrong
hoary gust
#

guys how to set a role colour

spring flax
unkempt canyonBOT
lament mesa
#

role.edit

spring flax
#

oh wait

#

!d discord.Role.edit

unkempt canyonBOT
#

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

Edits the role.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this.

All fields are optional.

Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
spring flax
#

i read that as how to see a role color mb

slate swan
#

How?

proven elm
#
@client.event
async def on_member_update(member, after):
    print(f'{member} has updated his account information!')



@client.event
async def on_user_update(member, after):
    print(f'{member} has updated his account information!')

#

Yoo guys tryna use on_user_update and member update but how do I show what has updated?

#

like "Twisterzz#1446 has changed his Profile Picture"

slate swan
#

How to do kick commend?

lament mesa
#

await member.kick()

spring flax
#

if you want to add more code to that event

proven elm
#

then when I print who updated their info it isnt defined

slate swan
unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change...
proven elm
#

print(f'{member} has updated his account information!')

maiden fable
#

No

proven elm
#

it now says member isnt defined

slate swan
maiden fable
#

yea

proven elm
#

ahhh

slate swan
#

before and after are member objcets

lament mesa
slate swan
#

objects*

#

so before is the member's before data, after is the member's new data basically

spring flax
#

example
if you want to look for nickname changes:

if before.display_name != after.display_name:
#code
proven elm
#

Thank you

#

async def on_user_update(member, before, after): is this what I do for my async

spring flax
#

no need member

proven elm
#

but then it says it isnt defined

slate swan
#

instead of using member, use before/after

#

before.display_name for example

proven elm
#

ahh okay thank you

spring flax
#
@client.event
async def on_member_update(before, after):
    print(f'{before} has updated his account information!')

Example ^

slate swan
#

thnx bros

boreal ravine
#

👍

slate swan
heavy folio
#

how do i fix this

slate swan
slate swan
lament mesa
unkempt canyonBOT
#

datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3.10/library/datetime.html#strftime-strptime-behavior).
river kindle
#

Hello guys
i am creating a bot in discord.py and i am doing a reaction role system, the code is right only that when the bot is online it does not send the message for the reaction role

Here the code:
@ client.event async def on_readyy (): channel = bot.get_channel ('872109565280387172') role = discord.utils.get (user.server.roles, name = "Bot tester") message = await bot.send_message (channel, "React to the message to verify yourself.") while True: reaction = await bot.wait_for_reaction (emoji = "✅", message = message) await bot.add_roles (reaction.message.author, role)

slate swan
#

There's so many wrong things in your code

#

1st what's with all the spaces

#

2nd it's on_ready not on_readyy

#

3rd is your bot instance named client or bot? Don't use both, use the one that you have, if it's client then bot.get_channel will be client.get_channel

gloomy coral
#
from PIL import ImageDraws
ImportError: cannot import name 'ImageDraws' from 'PIL' (/usr/local/lib/python3.8/dist-packages/PIL/__init__.py)
minor kestrel
#

Is there any fork of discord.py that seems good enough to use it, or is to soon?

gloomy coral
#

Help fix error

river kindle
slate swan
#

4th ids are ints not strings

slate swan
#

You can only have 1 on ready

#

If you want to have more use listeners

gloomy coral
#

can u help me?

river kindle
slate swan
#

It's wait_for

lament mesa
gloomy coral
# slate swan It's ImageDraw

Successfully installed Pillow-8.3.1
root@Zeroandone:~/chad# python3 bot.py
Traceback (most recent call last):
File "bot.py", line 20, in <module>
from PIL import ImageDraws
ImportError: cannot import name 'ImageDraws' from 'PIL' (/usr/local/lib/python3.8/dist-packages/PIL/init.py)
root@Zeroandone:~/chad#

river kindle
#

@slate swan i tried to put everything with client, but it doesn't send the message anyway

minor kestrel
slate swan
#

It's not ImageDraws

proven elm
#

Trying to do unban commands but it only recognises users if their in the discord how do I make it understand their discord IDs?

slate swan
river kindle
#

why?

slate swan
#

You didn't define user

gloomy coral
#

alr got it

slate swan
#

And all of the above that I mentioned

gloomy coral
#

Also

river kindle
gloomy coral
#

in a vps, all i gotta do is python bot.py right?

gloomy coral
#

async def cmd (ctx,user:discord.User)

gloomy coral
river kindle
#

thaanks

slate swan
devout iris
#

Can i do embed with discord py?

slate swan
#

Yes

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(**kwargs)```
Represents a Discord embed.

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

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

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

Still I would recommend that you don't use reactions in on_ready as it won't work the way you probably intend it to

#

Using on_raw_reaction_add would be more fitting

proven elm
# slate swan Use discord.User
@client.command()
async def unban(ctx, user):
    await ctx.discord.unban(user)
    await print({user}, "has been unbanned from the server")
#

'Context' object has no attribute 'discord'

slate swan
#

I-

#

That's bc u didn't put it where u were supposed to

lament mesa
slate swan
#

Where you define your params, user: discord.User

proven elm
#

ohhh ok

lament mesa
#

maybe you meant ctx.guild

#

and print isnt coro

proven elm
#

yea

#

oh yea

#

fixed

gloomy coral
#

Help me pls

lament mesa
#

with?

gloomy coral
#
Python-dotenv could not parse statement starting at line 2
Python-dotenv could not parse statement starting at line 4
Python-dotenv could not parse statement starting at line 2
Python-dotenv could not parse statement starting at line 4
valid niche
gloomy coral
#

it is

#

shld i..... send it?

#

alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU VWXYZ!@#$%&*()-_+="';:<>,.?{}[]"

valid niche
#

and that's incorrectly formatted

#

.env doesn't have quote marks

#

for instance it would be

TOKEN=abcDEFghiJKLMop
CHANNELID=123435658487
ROLEID=38737187183
SECRET=sdkjakSDGKJASDHFfjiusd84hjsfndJKH
IP=123.456.789.1
#

@gloomy coral that's how env is formatted

gloomy coral
#

Oh

#

damn

#

Guys

#

@valid niche

#

im using vultr, and when i close my putty session the bot goes offline! how can i fix?

valid niche
#

Virtual terminals

#

Like screen

#

Or more advanced: docker

gloomy coral
#

nooooooo

#

a better package manager?

valid niche
#

Wut?

gloomy coral
thorn yew
#

umm I need some help, I got this,

#

can someone explain whats the problem here?

#

this is for a music bot btw^

river kindle
#

Hi guys, I created a role reaction system in discord.py, practically you create the embed with the reaction, but the click on the reaction does not give me the role. Can anyone help me?

The code here:

async def on_ready():
    print('Bot online')
    await client.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.watching,
            name=f'in {len(client.guilds)} servers | !aiuto for help | !invita for invite'))

@client.event
async def on_raw_reaction_add(payload):

  if payload.member.bot:
    pass

  else:

    with open('reactrole.json') as react_file:

      data = json.load(react_file)
      for x in data:
        if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
          role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])


          await payload.member.add_roles(role)



@client.event
async def on_raw_reaction_remove(payload):

  if payload.member.bot:
    pass

  else:

    with open('reactrole.json') as react_file:

      data = json.load(react_file)
      for x in data:
        if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
          role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])


          await client.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(role)

@client.command()
async def reactrole(ctx, emoji, role: discord.Role, *, message):
  
  emb = discord.Embed(description=message)
  msg = await ctx.channel.send(embed=emb)
  await msg.add_reaction(emoji)

  with open('reactrole.json') as json_file:
    data = json_load(json_file)

    new_react_role =  {
      'role_name' :role.name, 
      'role_id' :role.id,
      'emoji' :emoji,
      'message_id' :msg.id
    } 

    data.append(new_react_role)


  with open('reactrole.json', 'w') as j:
    json.dump(data,j, indent=4)
valid niche
# gloomy coral how to do tht

Install screen from your package manager, like apt install screen. Then do screen -S name (and replace name with whatever you want to name it) to make a new screen. In the screen start your bot. Then press ctrl + a ctrl + d to detach so it runs in the background. If you ever need to go back you can do screen -r name to go to the screen with that name. And when you want to close a screen go into the screen and type exit

slate swan
thorn yew
#

uhh yea...

gloomy coral
#

a am using pm2

thorn yew
#

ill go ask somewhere else sry..

slate swan
river kindle
#

Hi guys, I created a role reaction system in discord.py, practically you create the embed with the reaction, but the click on the reaction does not give me the role. Can anyone help me?

The code here:

async def on_ready():
    print('Bot online')
    await client.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.watching,
            name=f'in {len(client.guilds)} servers | !aiuto for help | !invita for invite'))

@client.event
async def on_raw_reaction_add(payload):

  if payload.member.bot:
    pass

  else:

    with open('reactrole.json') as react_file:

      data = json.load(react_file)
      for x in data:
        if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
          role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])


          await payload.member.add_roles(role)



@client.event
async def on_raw_reaction_remove(payload):

  if payload.member.bot:
    pass

  else:

    with open('reactrole.json') as react_file:

      data = json.load(react_file)
      for x in data:
        if x['emoji'] == payload.emoji.name and x['messsage_id'] == payload.message_id:
          role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])


          await client.get_guild(payload.guild_id).get_member(payload.user_id).remove_roles(role)

@client.command()
async def reactrole(ctx, emoji, role: discord.Role, *, message):
  
  emb = discord.Embed(description=message)
  msg = await ctx.channel.send(embed=emb)
  await msg.add_reaction(emoji)

  with open('reactrole.json') as json_file:
    data = json_load(json_file)

    new_react_role =  {
      'role_name' :role.name, 
      'role_id' :role.id,
      'emoji' :emoji,
      'message_id' :msg.id
    } 

    data.append(new_react_role)


  with open('reactrole.json', 'w') as j:
    json.dump(data,j, indent=4)
gloomy coral
#
@commands.command(aliases=['enc', 'script'])
    async def encrypt(self,ctx, *, text_to_encrypt: str):
        valid_reactions = [':trash:']
        embed = discord.Embed(title="Encoding your message :zo_typing:",
                            description="This stays in between us. :wink:\n Keep this a secret. :zipper_mouth:")
        embed.color = discord.Color.dark_blue()
        embed.set_footer(text="You all saw NOTHING")
        embed.add_field(name="Encrypted Text", value='`' + enc.encrypt_text(text_to_encrypt) + '`')
        message = await ctx.send(embed=embed)
        await message.add_reaction(':trash:')

        def check(reaction, user):
            return reaction.message == message and str(
                reaction.emoji) == ':trash:' and user == ctx.author

        await self.bot.wait_for('reaction_add', check=check)

        await message.delete()```
#

why doesnt this delete the embed on reacting

slate swan
#

How to make buttons in disnake?

cobalt jacinth
#

guys..i am using matplot to save the plot and send it as an attachment..something weird is happening..plot of two successive commands is getting mixed

lament mesa
limber mountain
dry kelp
#

how can i check if the author is in the same vc with the bot?

lament mesa
#

ctx.author.voice.channel

dry kelp
#

if that ....

#

like i gotta check if the author is in the same vc with the bot

slate swan
# kindred epoch Vultr? Overprice?

Yeah, I pay $80 for specs that you can get for $30. Unfortunately you have to pay full time on other vps's since there's a 90 day money back.

dry kelp
#

help lol?

slate swan
#

its economy

hollow nexus
#

how can i ignore deprecation warnings and attribute errors?

hollow nexus
devout birch
kindred epoch
devout birch
slate swan
#

How can I make the bot edit the message

unkempt canyonBOT
#

Hey @stray stump! 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!

stray stump
#

huh

#

oh

devout birch
#

lol

stray stump
#
import discord
import time

TOKEN = ""

client = discord.Client()


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


client.run(TOKEN)


@client.event
async def on_reply(message):
    user_n = str(message.author).split("#")[0]
    user_m = str(message.content)
    channel = str(message.channel.name)

    if message.author == client.user:
        return

    if user_m.lower() == "Hello":
        await message.channel.send(f"Hello {user_n}, how's your day?")
        return```
#

i removed token btw ^

devout birch
#

can anyone help me with this?

slate swan
#

How can I make the bot edit the message

stray stump
#

anyway its not working

#

the bot doesnt reply 😔

slate swan
kindred epoch
devout birch
#

it should send a message

#

on button click

kindred epoch
#

Show code

devout birch
kindred epoch
unkempt canyonBOT
#

await edit(**fields)```
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.
kindred epoch
devout birch
kindred epoch
#

Why not here?

#

Noone gonna steal your code

devout birch
kindred epoch
#

Noone cares

devout birch
#

@kindred epoch

#

here'

#

ayo

#

respond

#

@kindred epoch

kindred epoch
#

What lib are you using

devout birch
devout birch
kindred epoch
#

Uh

stray stump
#
import discord
import time

TOKEN = ""

client = discord.Client()


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


client.run(TOKEN)


@client.event
async def on_reply(message):
    user_n = str(message.author).split("#")[0]
    user_m = str(message.content)
    chann = str(message.channel)

    if message.author == client.user:
        return

    if user_m.lower() == "Hello":
        await chann.send(f"Hello {user_n}, how's your day?")
        return```
#

it doesnt reply

kindred epoch
#

Idk anything about discord components, ask it in their support server

slate swan
#

not at the end of ur code

kindred epoch
#

Start by reading that

dapper cobalt
unkempt canyonBOT
#

await edit(**fields)```
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.
slate swan
compact field
#

hi guys how can i get all messages in channel ?

slate swan
ornate sparrow
#

hello can someone help

slate swan
ornate sparrow
zinc lion
#

so right here, I add a reaction ✅ but I also want to see if a user reacted with it too, how can I do that?py @bot.command() async def test(ctx): embedVar = discord.Embed(description='Please wait for an admin', color=0xc754f) msg1 = await ctx.send(embed=embedVar) await msg1.add_reaction('\N{White Heavy Check Mark}')

hasty iron
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
hasty iron
#

there is an example for reactions

slate swan
#

So my bad word filter keeps deleting anything even if it's not in the yeah.txt file. How can I fix it?

Code:


letters = ("à",  "á", "â", "ä", "æ", "ã", "å", "ā")

with open("yeah.txt") as file:
    test2 = file.read().split('\n')

@bot.listen("on_message")
async def on_message(message):

    guild = message.guild
    bypassedRole = discord.utils.get(guild.roles, name="Bypassed")


    if bypassedRole in message.author.roles:
        return

    for word in test2:
        regex_match_none = re.compile(fr"([{letters}]+{word})|({word}[{letters}]+)", re.IGNORECASE)
        if regex_match_none.search(message.content) is None:
            await message.delete()
            embed = discord.Embed(title="Message Deleted", color=0xD708CC, description= f"{message.author.mention}, You're not allowed to say that.")
            embed.timestamp = datetime.utcnow()
            await message.channel.send(embed=embed)```
zinc lion
# hasty iron there is an example for reactions

thanks man!!```py
@bot.command()
async def test(ctx):

await ctx.send('Send me that 👍 reaction, mate')

def check(reaction, user):
    return user == ctx.author and str(reaction.emoji) == '👍'

try:
    reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
    await ctx.send('👎')
else:
    await ctx.send('👍')``` this examples works but if I have the timeout as None, do I remove the except and else statements?
pale turtle
#

You can just not put it?

zinc lion
#
@bot.command()
async def test(ctx):


    await ctx.send('Send me that 👍 reaction, mate')

    def check(reaction, user):
        return user == ctx.author and str(reaction.emoji) == '👍'

    reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)
    await ctx.send('👎')```?
lament mesa
#

and you cant have try alone

amber imp
#

help pls

zinc lion
amber imp
#

@bot.command() async def invite(ctx): embed=discord.Embed(title="invite me", url="https://discord.com/api/oauth2/authorize?client_id=876383024089006100&permissions=8&scope=bot%20applications.commands", description="invite me to your server ", color=0x00e1ff) embed.set_author(name="bot") await ctx.send(embed=embed)

zinc lion
amber imp
#

File "main.py", line 130
await ctx.send(embed=embed)
^
SyntaxError: 'await' outside function

#

anyone help pls

lament mesa
#

you cant have await outside async functions

amber imp
#

done

#

bro it was indentation problem

lament mesa
#

ok

amber imp
#

File "main.py", line 129
embed.set_author(name="bot")
^
IndentationError: unindent does not match any outer indentation level

lament mesa
#

Send your code also

amber imp
lament mesa
#

indent the last 2 lines

amber imp
lament mesa
#

👍

zinc lion
#

How do you mention a role? py await ctx.send(@hollow hound) doesnt workSyntaxError: invalid syntax

gloomy coral
#

well its simple

#

u gotta put quotes lmao

#
await ctx.send("@hollow hound")
#

if its a valid role it shld work

river kindle
#

Hi guys, I'm doing a reaction role system, the code doesn't give errors, the command exists, but if I call it it doesn't give me any answer

async def reactionrole (ctx):
    if ctx.message.author.server_permissions.administrator:
        testEmbed = discord.Embed (color = discord.Color.red ())
        testEmbed.set_author (name = 'Test')
        testEmbed.add_field (name = 'Test', value = 'Test')

    msg = await client.send_message (ctx.message.channel, embed = testEmbed)
    await bot.add_reaction (msg, emoji = ':white_check_mark:')

@ client.event
async def on_reaction_add (reaction, user):
    Channel = client.get_channel ('872109565280387172')
    if reaction.message.channel.id! = Channel:
        return
    if reaction.emoji == ":white_check_mark:":
        Role = discord.utils.get (user.server.roles, name = "Bot tester")
        await client.add_roles (user, Role)```
zinc lion
gloomy coral
gloomy coral
river kindle
zinc lion
#

i did, doesnt work, no errors or nothing it just does @the_id

lament mesa
gloomy coral
#

wdym?