#discord-bots

1 messages · Page 555 of 1

lament mesa
#

print doesn't return anything

shy roost
#

forgot about that lmao

shy roost
lament mesa
#

!d contextlib.redirect_stdout

unkempt canyonBOT
#

contextlib.redirect_stdout(new_target)```
Context manager for temporarily redirecting [`sys.stdout`](https://docs.python.org/3/library/sys.html#sys.stdout "sys.stdout") to another file or file-like object.

This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.

For example, the output of [`help()`](https://docs.python.org/3/library/functions.html#help "help") normally is sent to *sys.stdout*. You can capture that output in a string by redirecting the output to an [`io.StringIO`](https://docs.python.org/3/library/io.html#io.StringIO "io.StringIO") object. The replacement stream is returned from the `__enter__` method and so is available as the target of the [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statement:

```py
with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()
```  To send the output of [`help()`](https://docs.python.org/3/library/functions.html#help "help") to a file on disk, redirect the output to a regular file...
slate swan
#

.

#

.

shy roost
#

@pliant gulch i did ```py
return 2 + 2

pliant gulch
#

Can you show your code?

shy roost
#
@commands.command(aliases=["e", "eval"])
    async def evaluate(self, ctx, *, code):
        codeblock = f"```{code}```"
        end_code = codeblock.strip("`")
        end_code = textwrap.indent(end_code, prefix="\t")
        evaluated_result = exec(f"async def eval():\n{end_code}")
        captured_errors = traceback.format_exc(limit=None, chain=True)
        embed = discord.Embed()
        embed.add_field(name="Code evaluation finished!", value=f"{evaluated_result}")
        await ctx.send(embed=embed)
pliant gulch
#

Like I said earlier exec returns None

#

you need to call eval in the embed fstring

shy roost
pliant gulch
#

No

#

Look at this example

shy roost
#

okay so like this: py exec(f"def eval():\n\t{code}eval()")?

pliant gulch
#

No

shy roost
#

sorry, i'm just a bit confused.

pliant gulch
#

Exec makes the eval function

#

So in your embed, separate from the exec

#

Call eval

#

Just replace where you have evaluated_result with await eval()

shy roost
#

ah okay

#

so like this: ```py
evaluated_result = exec(f"async def eval():\n{end_code}")
embed.add_field(name="Code evaluation finished!", value=eval())

pliant gulch
#

I would keep it in the f-string, and make sure to await eval

crystal cave
#

which website should i host my code (websites like heroku)

shy roost
final iron
#

This is actually a really good solution for an eval command

pliant gulch
final iron
#

Personally I just sent the result to a txt file and sent the contents

pliant gulch
#

And keeping it in the f string will cast the return to string when sending

#

So it won't error if you send something that can't be sent

shy roost
#

@pliant gulch it's saying that I can't pass nothing to eval()

pliant gulch
crystal cave
#

which website should i host my code (websites like heroku)

shy roost
shy roost
hollow palm
#

I'm trying to implement a search function into my bot, however when the command is called only the first word of the search is used. So for example if you search up "nice image", it will only search up "nice". How do I make it so the url parameter takes all the text after the command?

pliant gulch
#

and then call it with the name which you changed it to

shy roost
#

when I do this: ```py
evaluated_result = exec(f"async def eval_code():\n{end_code}")
embed.add_field(name="Code evaluation finished!", value=f"{await eval_code()}")

pliant gulch
#

I'd just ignore it for now, does it work?

shy roost
#

nope, it's saying that eval_code doesn't exist.

pliant gulch
#

Ok, seems like you will have to make a dictionary then

shy roost
#

damn okay

pliant gulch
#
variables = {}
exec("eval_code function here", variables)
shy roost
#

okay

pliant gulch
#

then call it via await variables["eval_code"]()

#

in your embed

#

You can add variables to variables if you want, so you can do stuff like referencing ctx

shy roost
#

okay, and should I define this dictionary before evaluated_result or in place of end_code?

pliant gulch
#

Do it above the exec as I have done in the example

#

And you don't need evaluated_result

shy roost
#

okay

pliant gulch
#

exec returns None

#

so evaluated_result is always None

shy roost
#

@pliant gulch god my brain is tired, why is this python formatting returning an error: ```py
value=f"{await variables"eval_code"})

pliant gulch
#

replace "eval_code" with 'eval_code'

#

what is it saying?

shy roost
#

LMAO NVM

pliant gulch
#

Does it work now?

shy roost
#

no

#

when I use a codeblock, it's saying that this line of code: ```py
embed.add_field(name="Code evaluation finished!", value=f"{await variables'eval_code'}")

pliant gulch
#

Strip it

slate swan
#

can you send the full error

pliant gulch
#

Same way you stripped the tilda's

shy roost
#

should I also strip the tildas from it?

pliant gulch
#

Yes

shy roost
#

okay, let me give it a shot

#
embed.add_field(name="Code evaluation finished!", value=f"{await variables['eval_code']().strip('`')}")
``` coroutine object has no attribute 'strip'
pliant gulch
#

?

#

You strip the string

#

^The part where you clean the codeblock

shy roost
#
@commands.command(aliases=["e", "eval"])
    async def evaluate(self, ctx, *, code):
        codeblock = f"```{code}```"
        end_code = codeblock.strip("`")
        end_code = textwrap.indent(end_code, prefix="\t")
        variables = {}
        evaluated_result = exec(f"async def eval_code():\n{end_code}", variables)
        captured_errors = traceback.format_exc(limit=None, chain=True)
        embed = discord.Embed()
        embed.add_field(name="Code evaluation finished!", value=f"{await variables['eval_code']().strip('`')}")
        await ctx.send(embed=embed)
#

which line from this code?

pliant gulch
#

Above the second assignment of end_code

#

just do end_code.strip again but with py

#

Or you can do it on the first strip if you want to save lines

shy roost
#

nah, i'll just do it before the second define statement

#
evaluated_result = exec(f"async def eval_code():\n{end_code}", variables)
``` now it's saying that this line contains invalid syntax, ``````py
pliant gulch
#

Can you print out end_code and show me what that looks like

shy roost
#

okay

pliant gulch
#

Why is there so many tildas?

#

Codeblocks should only have 6, 3 on top and 3 on the bottom

shy roost
#

idk

pliant gulch
#

Run the command with

return 2+2
shy roost
#

that's what I've been doing though

pliant gulch
#

That's odd so somehow end_code duplicates the tildas???

#

That makes no sense to me

shy roost
#

yeah same

#

@pliant gulch would you mind adding me?

pliant gulch
#

What for?

shy roost
#

idk, if I need help in the future, you seem really chill, that's all.

#

@pliant gulch alright, i'm going to head out now. You have more patience than jeff bezos has money in his bank account honestly. You are a legend, I really appreciate you sticking around for nearly 1:30 hours, thank you.

pliant gulch
#

👍 , and I don't give out help in DM's if you want help from me just ping me

#

I will sometimes be able to help out

shy roost
shy roost
pliant gulch
#

BEFORE YOU LEAVE I KNOW WHY ITS ERROING

#

its cause you define codeblock with tildas

shy roost
pliant gulch
#

Do all the stripping DIRECTLY on code

shy roost
#

code? where is that?

pliant gulch
#

the argument you pass to the command

shy roost
#
embed.add_field(name="Code evaluation finished!", value=f"{await variables['eval_code']()}")
``` like this line?
pliant gulch
#

async def evaluate(self, ctx, *, code):

#

code right here, do all the stripping on the code variable

slate swan
#

Does anyone know an efficient way to store a mute duration if the bot were to restart?

shy roost
#

ah okay, so I will just do ```py
async def evaluate(self, ctx, *, code.strip("`"))

pliant gulch
#

no where the end_code stuff is

slate swan
#

lol

pliant gulch
#

just replace codeblock with code

shy roost
#

OHHH

#
evaluated_result = exec(f"async def eval_code():\n{end_code}", variables)
``` now it's saying that this line has invalid syntax
pliant gulch
#

strip py as well

shy roost
#

from that line?

pliant gulch
#

end_code = code.strip("`")

#

end_code = end_code.strip("py")

slate swan
pliant gulch
slate swan
#

it'll strip anything that says "py" in the code too right?

pliant gulch
#

It would but you can just avoid typing py in your codeblock

shy roost
#

@pliant gulch THANK YOU SO MUCH, IT WORKED

#

FINALLY, AFTER NEARLY 2 HOURS

slate swan
#

and make it strip that

pliant gulch
slate swan
#

like make it string the image i just showed u

pliant gulch
#

The whole point of the strip("py") is to clean the codeblock

pliant gulch
#

Yea, so if you don't strip it then it will error

slate swan
#

but it'll strip anything that says py in the code like i said

pliant gulch
#

Yea, and I said to just avoid typing py

slate swan
#

breh

brave vessel
#

iirc you can't strip with more than one char, you might have to use removesuffix

final iron
#

I just used splicing

pliant gulch
#

!e ```py
a = "py-bruj"
print(a.strip("py"))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

-bruj
brave vessel
#

!e

test = "test"
print(test.strip("t"))
print(test.strip("st"))
unkempt canyonBOT
#

@brave vessel :white_check_mark: Your eval job has completed with return code 0.

001 | es
002 | e
brave vessel
#

not sure what that last one is doing lol

slate swan
#

!e py test = "python" print(test)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

python
brave vessel
# pliant gulch you can

ah, nvm
i think it can be a bit buggy tho since i remember running into an empty string with stripping, and that's why removesuffix /removeprefix was made i think

slate swan
#

see how it doesnt remove py?

pliant gulch
brave vessel
# pliant gulch Whered the t go??????

strip is apparently interpreted as a set of characters for when you give the string, and removes it from both ends, so s is removed from the end and t from the beginning

brave vessel
#

!e

a = "py-brujyp"
print(a.strip("py"))
unkempt canyonBOT
#

@brave vessel :white_check_mark: Your eval job has completed with return code 0.

-bruj
pliant gulch
#

Yikes

#

Ig you could probably do some regex stuff or manually parse the string if you want something very consistent

brave vessel
#

i think str.removesuffix or str.removeprefix works too

#

!e

a = "py-brujyp"
print(a.removeprefix("py"))
unkempt canyonBOT
#

@brave vessel :white_check_mark: Your eval job has completed with return code 0.

-brujyp
pliant gulch
#

yea, removeprefix seems ideal this case

brave vessel
#

i have to say the behavior of strip confused me a lot lmao until i realized that it just doesn't work for substrings

#

quite annoying but there's probably a reason for it

pliant gulch
#

@brave vessel Do you have any knowledge in concurrency stuff?

brave vessel
#

Barely, I'm mostly into asyncio but I'm somewhat of a beginner there

#

I've worked with threading before but I don't really use it, since it's not really my niche

pliant gulch
#

Ah, darn I just finished impl a concurrent request ratelimit handler for my discord API wrapper

#

needed someone to review it

brave vessel
#

where's it at?

pliant gulch
#

Uhh let me push the code I have rn to the repo then I'll send you the link

brave vessel
#

alright, awesome

#

Do you want me to review style, logic, or both

final pumice
#
client = discord.Client()

@client.event
async def on_ready():
  general_channel = client.get_channel("id")
  general_channel.send("Bot is online!")

Where would I put the await in this situation

brave vessel
final pumice
#

Why is that

brave vessel
#

general_channel.send(...) is the 'coroutine function' (an asynchronous function TLDR)
and doing await will call that coroutine function

pliant gulch
#

I despise how the internals of dpy look

final pumice
#

Is client.get_channel("id") not a coroutine function?

final pumice
#

Okay

pliant gulch
brave vessel
#

I'll check it out

pliant gulch
#

starts at line 113

brave vessel
#

Where should I put the review for it?

#

since it's not in a PR

final pumice
#

In the documentation, will it tell me what methods are coroutine functions?

final pumice
#

Awesome

#

Alr thanks

pliant gulch
brave vessel
#

Sounds good to me

#

so it's just from line 113 onwards?

pliant gulch
#

Mhm

#

Opened the PR

brave vessel
# pliant gulch Opened the PR

I might not be the best with logic considering I have heard of semaphores and the likes but haven't worked with them too much, so it'll mostly be logic with easier ways to do it in Python itself and maybe a few asynchronous comments if I understand it, is that fine?

#

I might try and do a bit of reading while reviewing so I can also make some comments on the concurrent handler

pliant gulch
#

If you want to move to DM's that is alright as well since it might flood this chat

brave vessel
#

Oh yeah true

pliant gulch
#

My dm's are off so you will have to add me if thats alright

final pumice
#

How do I get the ID of a channel

#

@brave vessel

brave vessel
final pumice
#

when I do get_channel(id)

#

it needs an id

brave vessel
#

oh

#

well iirc you might need to hardcode the ID or ask for it

final pumice
#

Eeeeeeeek

final pumice
brave vessel
#

Copy the ID of the channel

#

and then copy and paste it into the argument of the ufnction

vagrant galleon
#

could anyone help me with this?

final pumice
brave vessel
#

enable developer mode

#

it's in the settings of discord i think

final pumice
#

Ah thanks

brave vessel
#

np

final pumice
#

One more thing

#

If I wanted to ask for it, how would I do that?

pale zenith
final pumice
pale zenith
#

make a command that asks the user for the ID/mention/whatever

#

and store it in a database

#

well actually

#

i dont even know what you you're trying to do in the first place

#

so idk if thats even what you'd want/need

brave vessel
final pumice
#

ok

final pumice
pale zenith
#

🤔 probably hard code the id is the easiest lol

#

IDs are int btw

#

(also for commands you probably want commands.Bot not discord.Client btw)

slate swan
#

How can I check if anything from a list is in the content of a message

pale zenith
#

any takes an iterable^

#

see the 2nd to last example

slate swan
#

Ok and in an on_message how could I use that

pale zenith
#

just using it blobsweatsip its just a python thing not d.py

slate swan
#

On message takes the param message rifht

pale zenith
#

the string can be your .content

#

yes only message

slate swan
#

so would message.content work

pale zenith
#

yep

slate swan
#

Ok thanks

pale zenith
#

np

simple kettle
#

Does anyone know how I can tell how long it takes a user to answer a .wait_for()

spring verge
#

anyone else using hikari now?

simple kettle
#

Lets say it took a user 4 seconds to respond. How would I get that value?

try:
  message = await bot.wait_for("message", cheeck=check, timeout=10.00)
expect asyncio.TimeoutError:
  await ctx.channel.send("Took to long")
else:
  print("Do stuff")
brave vessel
#

The wait_for command won’t execute any code after it until it receives the event or times out

simple kettle
#

alright ill do that thanks

slate swan
#
@client.event
  async def on_message(ctx, message):
    if urls in message.content:
      await message.delete()
      await ctx.send("server protected from phisher")
    else:
      return
    client.process_commands(message)

What did I do wrong nothing works

boreal ravine
stable delta
#

actually you can't have ctx for on_message

slate swan
#

Anything else

stable delta
#

so take out ctx and sintead put await message.channel.send()

boreal ravine
slate swan
#

Ok anything else

stable delta
slate swan
#

Mhm

stable delta
#

then it should work

slate swan
#

Everything else works but it doesn't do the deleting or sending no errors

inner geyser
#

hey there, actually I was trying to get some data using the lichess api, I was using the aiohttp lib, but when I ran the code it gave me a ssl error, whereas when I ran the same code using requests module and using Curl directly, it worked perfectly fine

import discord, aiohttp
import json
from discord.ext import commands

class lichess(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def lichess_profile(self, ctx, user):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(f'https://lichess.org/api/puzzle/daily') as json_data:
                    prof = json.loads(await json_data.text())
                    await ctx.send("something")
                    print(prof)
        except Exception as e:
            print(e)
                    
def setup(client):
    client.add_cog(lichess(client))

My error was this -

Cannot connect to host lichess.org:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1122)')]
boreal ravine
#

whats wrong

inner geyser
boreal ravine
#

its a website problem ig

inner geyser
brisk fiber
#

list in str will never be True

#

odd that it doesn't throw an error though

slate swan
#

?

brisk fiber
#

is urls a list?

slate swan
#

No a string

brisk fiber
#

ah ok

slate swan
#

It says urls because I plan to make it ha ve several urls

brisk fiber
#

in one string?

slate swan
#

No

brisk fiber
slate swan
#

Want me to explain my project shortly

brisk fiber
#

no, it's okay

#

just make sure you aren't using the in keyword to compare things that never have a chance of being true

brisk fiber
paper olive
#

hi is this where to ask question about problems of discord bots?

slate swan
#

yes

boreal ravine
#

hey guys

#

How do I get a stickers' ID?

slate swan
unkempt canyonBOT
boreal ravine
#

how do I get it in discord though

paper olive
#

Traceback (most recent call last):
File "main.py", line 2, in <module>
import discord
ModuleNotFoundError: No module named 'discord'

KeyboardInterrupt

KeyboardInterrupt

slate swan
#

!d discord.Message.stickers

unkempt canyonBOT
slate swan
paper olive
slate swan
#

Pip install discord

boreal ravine
paper olive
boreal ravine
#

then install it first

sick birch
paper olive
sick birch
#

that's how to install if you want

#

more complete instructions can be found on the github page

valid perch
#

It's not discord, its discord.py

#

Although it works ig

paper olive
#

so i need to download an app?

pale zenith
valid perch
#

Tis why iim saying it aint the way

boreal ravine
#

makes sense

slate swan
#

Y'all got any idea how to set up a warning system, and after 3 warnings it auto mutes you?

boreal ravine
#

check if the user has 3+ warnings when you warn them -> mute them

inland venture
#
 if user_message.lower() == '*specs':
        embed = discord.Embed(title="Sunflower Duck's PC specs", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
                              description="SSD: M.2 1000GB Hard Drive MOBO: B460M Pro Vdh Wifi GPU: Intel UHD 630 Case: H510 Elite RAM: 16GB CPU: Intel core i5 10400",
                              embed.add_field(name="Field 2 Title", value="It is inline with Field 3", inline=True,
                              embed.add_field(name="Field 3 Title", value="It is inline with Field 2", inline=True,
                              color=0xFF5733)
        await message.channel.send(embed=embed)
        return
#

position error

boreal ravine
inland venture
#

it says I put embed.add_field in wrong place

boreal ravine
#

whats a position error

inland venture
#

wrong spacing

boreal ravine
#

you need to unindent embed.add_field

#

same line where you defined embed

inland venture
#

await message.channel.send(embed=embed)
^
SyntaxError: positional argument follows keyword argument

boreal ravine
cold patrol
#

does anyone know how to make your discord bot stay awake?

valid perch
#

Wdym stay awake?

cold patrol
#

i mean

#

i used some website for coding

#

but when i close the website, the bot also shutted down

inner geyser
#

Hey there, actually I was thinking to integrate mongodb in my discord.py bot, but just wanted to know, that if pymongo works asynchronously or not

reef shell
#

motor is asynchronous ig

#

!pypi motor

unkempt canyonBOT
torpid dew
#

Hi, I am trying to make a snipe command where it retrieves the last deleted message, here is the code so far, what is wrong with it?

@client.event
async def on_message_delete(message):
  client.sniped_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.create_at)

@client.command()
async def snipe(ctx):
  contents, author, channel_name, time = client.sniped_messages[ctx.guild.id]
  
  embed = discord.Embed(description=contents, colour=discord.Colour.blue(), timestamp = time)
  embed.set_author(name=f"{author.name}#{author.discriminator}", icon_url=author.avatar_url)
  embed.set_footer(text=f"Deleted in : #{channel_name}")
  await ctx.channel.send(embed=embed)

thanks

inner geyser
boreal ravine
slate swan
#

lol

#

Lmao

inner geyser
#

lmao

torpid dew
#

the code tutorial

boreal ravine
#

cool

#

but whats the error/what isn't working

torpid dew
slate swan
#

You need await client.process_commands(message) in your on_message event

#

Although you could just replace .event with .listen('on_message') which is what's more recommended

stiff nexus
#
    def embed(self, ctx: Context, **kwargs) -> discord.Embed:
        """This is how we deliver features like custom footer and custom color :)"""
        embed = discord.Embed(**kwargs)
        embed.color = embed_color
        return embed
``` this should override all the embeds right? or do i need to set in the cmd `color = self.bot.color` ???
torpid dew
#

Hi, I am trying to make a simple command that makes the bot post a custom animated emoji (I know the emoji format, discord doesnt let me show it so it will show up as :Fire:

@client.command()
async def wfire(ctx):
  if ctx == 'wfire':
    await ctx.send(":Fire:")

thanks

slate swan
#

you would want a second parameter

#

async def wfire(ctx, emoji):

#

and you would check for the emoji's content

#

if emoji == 'wfire':

boreal ravine
#

you mean :fire:

torpid dew
#

thanks

#

I'll give it a shot

torpid dew
slate swan
#

tell me what you did

#

there's no way I was wrong there lemon_angrysad

torpid dew
#

ok

#
@client.command()
async def wfire(ctx, emoji):
  if ctx == 'wfire':
    await ctx.send(":Fire:")
slate swan
torpid dew
#

again, discord doesnt let me said the emoji format

torpid dew
slate swan
#

yes

#

Literally just replace ctx to emoji in your current if statement

slate swan
#

Apparently not

torpid dew
slate swan
#

Apparently not

#

Otherwise it would've worked 2DWink

torpid dew
#
@client.command()
async def wfire(ctx, emoji):
  if emoji == 'wfire':
    await ctx.send(":Fire:")
slate swan
#

yes

#

then you use !wfire wfire

#

So, what happens now

torpid dew
#

is there any way to remove the 2nd wfire?

slate swan
#

Just remove the if statement and parameter

#

And send the emote directly

#

well then you wouldn't need the if statement

#
@client.command()
async def wfire(ctx):
    await ctx.send(":Fire:")```
#

simplest ever command

#

Why would you need a command that sends an emote you can send by yourself though CL5_MonkaScanning

torpid dew
#

oh yeah, it was an event then i changed it to command, i forgot to remove the if

slate swan
#

🔥

#

No nitro needed

torpid dew
torpid dew
slate swan
#

That's not how to send custom emotes though

torpid dew
#

but discord doesnt let me send it like that

#

cause i dont have nitro

#

when i try that it just goes to :Fire:

slate swan
#

Just get the emote id, put <a:emote_name:emote_id>

#

^

#

a: only if it's animated

torpid dew
torpid dew
slate swan
torpid dew
#

\:emoji_name:

#

to get id

slate swan
#

and name

#

and format

torpid dew
slate swan
torpid dew
#

i know

devout iris
#

Can i reboot my bot with a command?

maiden fable
slate swan
#

I am trying to set up channel permissions, but I can't get it to work.
What's wrong with this code?

slate swan
maiden fable
slate swan
#

reload cogs

maiden fable
#

What if they changed the imports?

devout iris
#

Btw, i'm new in discord.py so i haven't a cogs folder

slate swan
#

then... that sucks

maiden fable
slate swan
#

):

maiden fable
slate swan
maiden fable
#

Wym

slate swan
#

You already have channel, so declaring support_channel is redundant and therefore not needed

inner geyser
#

plz tell me if there is!

slate swan
#

What operating system and version are you using

inner geyser
#

py 3.9.0

slate swan
#

Download and install this certificate here:
https://crt.sh/?id=2835394

It can be installed by double clicking the file and installing it to Local Computer.

inner geyser
slate swan
#

Well certificate is expired

#

So you can't access the website

#

Through SSL

inner geyser
maiden fable
#

No worries

#

I am also getting that error literally everywhere, even with my API

#

In the ClientSession class, set the connector kwarg to something like this connector=TCPConnector(ssl=False)

#

This will connect without SSL

slate swan
#

Why would you not use SSL

#

Just install the certificate 3HC_what

maiden fable
slate swan
#

Well that's unfortunate KEKL

maiden fable
#

But is it a coincidence that all of a sudden it stops working for me on my local PC but it works perfectly on my VPS? I don't think so

#

Also, when I to to the API URL manually, it shows the SSL Lock symbol, and also it's hosted on repl and the domain on cloudflare. So I don't think that's an API problem

slate swan
#

You realize that the root certificate of Let's Encrypt expired a few weeks ago

#

So if you don't have an OS update or similar you can't go on multiple websites because of that

#

Which means old devices are pretty much not able to access these websites

slate swan
maiden fable
#

Ah thanks

slate swan
maiden fable
slate swan
#

Well pretty sure replit uses cloudflare

maiden fable
#

Yup, it does

#

So u think installing those certs should fix the issue?

slate swan
#

Possible

maiden fable
#

But then I use Windows 10 on my local machine

#

Sooo I don't really know 😐

shy junco
#

How do i make it so a user can only react once to a message

slate swan
#

You mean use one reaction emote only per user

shy junco
#

yea

#

they can only react with one emoji on a message

slate swan
#

Use the reaction add event and check if the message already has a reaction from the user, if yes: delete it

inner geyser
shy junco
#

and how do i remove the previous reaction

inner geyser
slate swan
slate swan
shy junco
#

docs?

inner geyser
unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

slate swan
#

Read the docs

shy junco
#

oh

slate swan
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

Well as I said, it's not an API issue

inner geyser
#

tru

slate swan
#

It's because the root certificate expired, this certificate is stored on each device

#

And if you can't update your device with security updates or similar, then the certificate won't get updated

wanton pebble
#

so im tryna do something that lets me use the id on a website so every time i get the user id, it doesn't nothing to the id just affects a database but the error says guild isnt irritable

the line thats wrong is

for member in ctx.guild:
#

i did enable all intents

leaden jasper
#

did you try testing with print statements

wanton pebble
#

lemme try lmao

honest rover
#

u are looping tru the guild object

#

not the members of the guild

wanton pebble
#

so how can i go through members?

leaden jasper
#

!d discord.Guild

unkempt canyonBOT
#

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

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

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
honest rover
#

guild.members

leaden jasper
#

!d discord.Guild.members

unkempt canyonBOT
#

property members: List[discord.member.Member]```
A list of members that belong to this guild.
shy junco
wanton pebble
#

thank you both

#

:)

honest rover
#

oke

haughty sedge
#

does await client.wait_for stops the further code from execution?

edgy trellis
#

for

farmm = client.get_channel(id)

how to specify guild where it should search for channel?

honest rover
#

get_channel is also a method of discord.Guild

#

so guild.get_channel()

slate swan
#

who know how to make card bot?

haughty sedge
#
wait = await client.wait_for('message',check=Check,timeout=15)
print(wait.content)```
is it going to print after the user sent the message ?
honest rover
#

yeah

haughty sedge
#

alright

honest rover
#

but like any user

#

literally any message the bot sees

#

oh wait theres a check nvm

slate swan
#

Hey guys, I'm facing an issue with my bot (discord.py), can someone help me?

#

Don't ask to ask, just send your question

#

Of course someone can help you, just not if you don't say for what you need help for

#

It replies this

#

message.content

#

In your embed

#

As I said

#

This is the code I'm using

haughty sedge
#
def Check(message: discord.Message):
  return message.channel == 845971398680641572 and message.content == "hello"```
whats wrong ;-;
slate swan
#

In your Suggestion field

haughty sedge
slate swan
#

Wow, can't believe it was so simple!

#

Thanks million times guys!

#

Oh and, you can also change your if statement @slate swan

#

Remove the str()

#

And remove the quotes from your id

#

So just

if message.channel.id == id
fading kiln
#

why is this not being sent

slate swan
#

Do you have an on_message event?

fading kiln
#

yea

slate swan
#

Do you have pocess_commands(message)

fading kiln
slate swan
#

And is your client variable actually Bot

fading kiln
#

no

#

its client

slate swan
#

Make it to a bot

#

If I remember correctly client can't make commands

fading kiln
#

this one ?

slate swan
#

See, it's a bot

fading kiln
#

ok

slate swan
#

Ok, another question.
What command can I use to show live number of reactions to a particular message?

#

So don't name your variable client

#

But anyways

valid perch
#

You will need this

manic wing
# fading kiln this one ?

following naming conventions, you should press ctrl + r and replace everything that says client -> bot.

fading kiln
#

so is my variable named client or bot

slate swan
#

In your on_message event add await client.process_commands(message)

manic wing
fading kiln
#

ok

slate swan
#

And consider renaming your variable to bot

unkempt canyonBOT
slate swan
#

Returns a list, so get the length of that

slate swan
#

Process your commands KEKL

fading kiln
#

lol

#

if I remove o nmessage

#

will it work

slate swan
#

Then you don't need it

fading kiln
#

lol

#

this is called gamer moment

slate swan
#

No?

valid perch
#

You could also just add that line of code..

fading kiln
slate swan
valid perch
#

You can remove it no matter what, is just code

fading kiln
#

yay

#

works now

edgy trellis
#

why this error occurs and how to fix this

name 'farmm' is not defined

Code

import discord
from discord.ext import commands, tasks
from discord.utils import get
from discord.ext.tasks import loop
import asyncio

client = commands.Bot(command_prefix=">", case_insensitive=True, self_bot=True)

@client.event
async def on_ready():
 print('Welcome master, the bot is online.')

for guild in client.guilds:
 if guild.id == '837280815699591188':
  farmm = guild.get_channel(897360659157749800)
  break

@tasks.loop(seconds = 32)
async def farm():
 await farmm.send('.work')
 await asyncio.sleep(3)
 await farmm.send('.dep all')

farm.start()

client.run(token)

Bot is in that guild

valid perch
#

Variable is out of scope

#

Also id's are int not str

unkempt canyonBOT
rain ridge
#

i wanna know how to get contents of a message sent by user and use it in the response.

edgy trellis
#

it is not self bot but test if bot will say bot command will it work

slate swan
#

Please don't think we're dumb, thanks

#

We won't help for that

edgy trellis
slate swan
#

Do your own research

#

where can I learn python?

#

!resources

unkempt canyonBOT
#
Resources

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

rain ridge
slate swan
#

tysm ^^

coral vessel
#

hello i just create simple bot with Python, i want to ask about, How My bot can Play/Listinening to something?

slate swan
#

Is there any way I can update this, as well as change Embed color?
I have not worked with Embed messages before.
Though I have written code for editing simple messages, but kinda skeptical with embeds.

#

This is my code for editing simple messages

slate swan
# coral vessel hello i just create simple bot with Python, i want to ask about, How My bot can ...
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))

# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))

# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))

# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))
coral vessel
rain ridge
#

ok so u meant the status

coral vessel
rain ridge
#

copy the line of code u want as status

#

not all

slate swan
rain ridge
#

to change the color of embed
embed=discord.Embed(title='Your title', description="Your description", color=0x552E12)

unkempt canyonBOT
#

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

Edits the message.

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

Changed in version 1.3: The `suppress` keyword-only parameter was added.
valid perch
#

!d discord.Message.embeds

unkempt canyonBOT
slate swan
valid perch
#

Send is a method

valid perch
#

Ctx isnt defined

#

Etc

rain ridge
#

yea but i want to cut/slice it and use it in response too

valid perch
#

Well its a string, you can slice it however you want

slate swan
#

yea i see i did i few things wrong

#

thx

coral vessel
valid perch
zinc mural
#

can somebody help pls

leaden jasper
#

@zinc mural cog name not found

valid perch
#

Can we see your code for the cog?

zinc mural
#
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

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

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

@client.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)
valid perch
#

Can we see your code for the cog?

zinc mural
#
import discord
import asyncio
from discord.client import Client
import requests
from discord.ext import commands
import os 

class test(commands.Cog):
    def __init__(self, client):
        self.bot = client




def setup(client):
    client.add_cog(test(client))
#

@valid perch

valid perch
#

Uh huh, and where does that file live?

#

In a folder called cogs?

zinc mural
coral vessel
slate swan
#

Nah, the relative filepath @zinc mural

valid perch
#

Uh huh, and where does that file live?
In a folder called cogs?

#

@zinc mural

#

This should be fun

leaden jasper
#

@zinc mural it needs to be in a cogs folder

runic jackal
#

How do I make it that a message is always split at the 10th place as an example?

sinful willow
#
from discord.ext import commands
import time

client = commands.Bot(command_prefix='?')

@client.command(aliases=['gav', 'Am i good at valorant?', 'GAV?'])
async def GAV(ctx):
    await ctx.send('Which Rank Are You')

client.run('noway.im.giving.my.bots.token.for.free.lmao')```

How do i make it so that, the answer of ?GAV is Iron, Bronze, Silver, Gold, Platinum, Diamond, Immortal, Radiant or it says your wrong or something.
slate swan
#

@zinc mural Show us the file structure of your project.

leaden jasper
#

@zinc mural or show file path

slate swan
#

wrong indents

sinful willow
#

also is there a way i can make my .json file which i got form discohook and make that display as an embed?

slate swan
slate swan
#

what indent level is it at?

#

My message is getting deleted

#

Without being able to copy it, the indents look good to me. There's an excess indent towards the bottom but it looks good.

haughty geyser
#

@slate swan Please send it without the bitly invite link

slate swan
#

Oh ok, thanks for help

#
async def on_message(message):
  if message.channel.id == 815284413586866246:
    await message.add_reaction(':white_check_mark:')
    await message.add_reaction(':x:')


    pfp = message.author.avatar_url
    embedd=discord.Embed(title="JEE Server", url="", color=discord.Color.blue())
    
    embedd.set_author(name= message.author.display_name, icon_url=pfp)
    embedd.set_thumbnail(url=pfp)
    embedd.add_field(name="Suggestion", value=message.content, inline=False)
    embedd.add_field(name="Suggestion Status", value="Pending", inline=False)
    

    sendChannel = bot.get_channel(815284513868873768)
    await sendChannel.send(embed = embedd)
    
    @bot.command()#6600
    async def suggestion(ctx, messageid:int=None):
      if messageid == None:
        await ctx.send("Something's amiss")
        return
      role = discord.utils.get(ctx.guild.roles, name=botManager)
    
      sendChannel = 815284513868873768
      msg = await sendChannel.fetch_message(messageid) 
   
      if role in ctx.message.author.roles or str(ctx.message.author.id) in msg.content:
        text = ctx.message.content
        embedd.edit_field(name="Suggestion Status", value =text, inline=False)
        
        await msg.edit(content=text)
        if role not in ctx.message.author.roles:
            await ctx.send("Please do not misue this command.", delete_after=10)
        else:
          await ctx.send("Please do not misue this command.")```
cinder horizon
#

Im tryna make a giveaway command and i wanted help on this

inner geyser
#

hey there, I am not able to extract data from a api, which has the element name as 'createdAt'

#

data here

rain ridge
#

how can i start a timer after a command is called?

slate swan
#

what inf loop will not cause commands to not work?
while loop currently

valid perch
#

What do ou wanna do

slate swan
#

what permission is needed to see who is banned?

slate swan
valid perch
#

tasks.loop

slate swan
#

^^

snow cosmos
#

discord.Permissions.read_message_history

slate swan
#

i did it like this and it still don't dm people when they join

snow cosmos
slate swan
#

yea

snow cosmos
#

thats not the correct way

#

you can just do await member.send(f"Hi {member.name}, how are you !")

slate swan
#

so i dont have to do create_dm

boreal ravine
#

just send the message to the member object

inner geyser
#

Does anyone know how to fix this Errno 22 invalid arg error
I was getting a timestamp from a api, and was converting it thru

import time
converted_time = time.ctime(data['createdAt'])
ionic wadi
#
    msg_id, channel_id, category_id = 'txt/ticket_config.txt'[payload.guild_id]
IndexError: string index out of range
#

Can someone explain?

slate swan
#

how to check if person that executed of message reacted with specific message
i mean if i have code like that

@client.command()
async def test(ctx):
 teest = client.get_channel(id)
 varabel = await teest.send('test message')
 await varabel.add_reaction('❌')

and i want to check if person who executed the command reacted to that message with that emoji how do i do that?

ionic wadi
#

I need to fix that piece of code, the rest of the code works fine at all moments.

inner geyser
ionic wadi
#

I just need to know how I have to define It If It doesnt recognize the strings

inner geyser
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

theres no class called Payload

valid perch
#

!d discord.RawReactionActionEvent

unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
valid perch
valid perch
mint stump
#

is this a bug?

valid perch
valid perch
#

Are you
a) referring to the time differences
b) The multiple sends

valid perch
#

On the assumption your code should send once, it means you have multiple instances of your bot running

slate swan
#

k got it

valid perch
#

Stop running your bot before you run it again

slate swan
#

how to get message id of message that bot send?

#

do you have developer mode on

slate swan
#

oh my bad

manic wing
#

where messageable is an instance of discord.abc.Messageable

#

!d discord.Message msg returns an instance of discord.Message

unkempt canyonBOT
#

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

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
slate swan
#

ok

#

thanks

#

btw

#

how do i send message in
on_raw_reaction_add event?

mint stump
slate swan
long fog
#

i get error py @client.event async def on_member_join(member): print("Recognised that a member called " + member.name + " joined") try: await client.send_message(member, newUserMessage) print("Sent message to " + member.name) except: print("Couldn't message " + member.name) embed=discord.Embed title="Welcome "+member.name+"!" description="Welcome to 404." color=discord.Color.green()

slate swan
#

!d discord.Client.get_channel

unkempt canyonBOT
long fog
#

@client.event
async def on_member_join(member):
print("Recognised that a member called " + member.name + " joined")
try:
await client.send_message(member, newUserMessage)
print("Sent message to " + member.name)
except:
print("Couldn't message " + member.name)
embed=discord.Embed
title="Welcome "+member.name+"!"
description="Welcome to 404."
color=discord.Color.green()

manic wing
slate swan
rain ridge
#
import asyncio

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

@bot.command()
async def test(ctx):
    await ctx.send('Hello!')

async def timer(ctx, timeInput):
    try:
        try:
            time = int(timeInput)
        except:
            convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
            time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]
        if time > 86400:
            await ctx.send("I can\'t do timers over a day long")
            return
        if time <= 0:
            await ctx.send("Timers don\'t go into negatives :/")
            return
        if time >= 3600:
            message = await ctx.send(f"Timer: {time//3600} hours {time%3600//60} minutes {time%60} seconds")
        elif time >= 60:
            message = await ctx.send(f"Timer: {time//60} minutes {time%60} seconds")
        elif time < 60:
            message = await ctx.send(f"Timer: {time} seconds")
        while True:
            try:
                await asyncio.sleep(5)
                time -= 5
                if time >= 3600:
                    await message.edit(content=f"Timer: {time//3600} hours {time %3600//60} minutes {time%60} seconds")
                elif time >= 60:
                    await message.edit(content=f"Timer: {time//60} minutes {time%60} seconds")
                elif time < 60:
                    await message.edit(content=f"Timer: {time} seconds")
                if time <= 0:
                    await message.edit(content="Ended!")
                    await ctx.send(f"{ctx.author.mention} Your countdown Has ended!")
                    break
            except:
                break
    except:
        await ctx.send(f"Alright, first you gotta let me know how I\'m gonna time **{timeInput}**....")

bot.run('token')```
rain ridge
#

ooh

slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

manic wing
rain ridge
#

uhm uhh

manic wing
#

nice copy & paste.

slate swan
#

cause someone sent it

rain ridge
#

it gives me an error when running timer command

slate swan
#

commands.command is meant to be used in cogs

#

you should use @bot.command() as per your code

long fog
rain ridge
#

i am new to bot development

slate swan
# long fog

all this should be wrapped inside the embed variable

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

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

bool(b) Returns whether the embed has any data set.

New in version 2.0.

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/master/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
#

dont copy paste code , look into the docs
if you dont understand anything people here would for sure always help

#

what that error means?

Ignoring exception in command sta:
Traceback (most recent call last):
  File "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\barte\source\repos\bottt\bottt\bottt.py", line 44, in sta
    await varabel.add_reaction('❌')
  File "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\message.py", line 1149, in add_reaction
    await self._state.http.add_reaction(self.channel.id, self.id, emoji)
  File "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 241, 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 "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\barte\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

it stops at this part

await varabel.add_reaction('❌')

"varabel" definde line above

varabel = await arg.send('started loop')
rain ridge
slate swan
#

error is already clear

valid perch
slate swan
slate swan
valid perch
#

Fun

slate swan
rain ridge
#

ok it worked

slate swan
rain ridge
#

so whenever i have to declare a function as a command i have to put
@bot.command()

slate swan
#

in your main file , sure

valid perch
#

Dont forget the ()

rain ridge
#

yea

slate swan
#

Hey I am trying to make a tempban command on dpy with storing values in mongo

    @tasks.loop(seconds=600)
    async def checker(self):
        try:
            all = self.coll.find({})  # return all documents inside the db
            current_time = datetime.datetime.now()
            async for x in all:
                if current >= x["BannedUntil"]:  # do stuff after this
                    unbanuser = z["user_id"]
                    await z.unban(reason="Tempban for new account expired.")
                else:
                    pass
                
        except Exception:
            pass

Here is my checker to loop every 10mins not sure if I am unbanning the user in the right way?

        tempbanned = {"user_id": user.id, "BannedUntil": final_time}

Storing it like this

slate swan
#

I am new to dbs thats the reason I am not sure if I am doing it the right way

slate swan
#

any error you get?

slate swan
slate swan
#

you need to fetch the user first

slate swan
slate swan
#

no , sir , you are getting the user id

slate swan
slate swan
zenith zinc
slate swan
zenith zinc
#

ou sorry wrong member

zenith zinc
# long fog

embed = discord.Embed(title="",description="",color=discord.Color.green())

slate swan
#

since member would be a user , and it has no unban attribute

#

you can get the guild object by

#

!d discord.Client.get_guild

unkempt canyonBOT
zenith zinc
#

sorry

slate swan
#

Unbans this member. Equivalent to Guild.unban().
Thats what it said

zenith zinc
#

ok

velvet crest
#

Any clue why guild returned as a nonetype object ? got error while reeboting the bot

slate swan
zenith zinc
slate swan
#

turn on member intents

zenith zinc
#

jes

velvet crest
slate swan
slate swan
slate swan
#

discord.Object(id = an id) will return the User object

#

OH

velvet crest
slate swan
velvet crest
slate swan
#

you would get the exact point where the error occurs

#

would be easier to help

velvet crest
#

/left

slate swan
#
                        member = discord.Object(id={unbanuser})
                        guild = get_guild(int)
                        await guild.unban(reason="Tempban for new account expired.")

Is this what you meant?

velvet crest
slate swan
slate swan
#

and it takes the member as an argument

#

by it i mean unban

#

Gotcha thanks so much

slate swan
velvet crest
#

lol

slate swan
slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

also use aiohttp instead of requests

storm sluice
#

whats wrong with it?

bot = commands.Bot(command_prefix='-',help_command=None)```

```py
@bot.command()
async def start(ctx):
  link = await bot.togetherControl.create_link(ctx.author.voice.channel.id, 'youtube')
  await ctx.channel.send(f"Click the blue link!\n{link}")```
slate swan
#

the error says it all

storm sluice
tall canopy
#

hi may i ask how to make the bot react to it own message?

await client.add_reaction('1️⃣')

But like this it say the bot has no attritube to react
Can someone help me?
bright palm
#

Store the message or fetch the message so you can react to it

tall canopy
#

oh okay. im try it .thanks bro .

slate swan
#

maybe changing the internals

cloud dawn
slate swan
#

if they could read the docs , instead of just copying the part they need
it would be more helpful

cloud dawn
#

The discord-together is meant to be used in OOP so he hasn't defined togetherControl in self.

#

It's a weird pypi anyways since it's basically one function.

slate swan
#

or can define a variable for that

#

in case they dont subclass it

#

read the error

#

you havent defined role in else

zinc mural
#

help me pls

#
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

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

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

@client.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run
cloud dawn
#

I recommend not copying code especially bad code.

zinc mural
#

yea

valid niche
cloud dawn
# zinc mural yea

do me a favor and do print(os.getcwd()) all questions will be answered.

#

Most likely he is executing this code inside his debugger.

valid niche
cloud dawn
zinc mural
cloud dawn
cloud dawn
slate swan
#

it happens in python3.9 if the cog folder is in same directory

valid niche
cloud dawn
coral vessel
#

How to make welcome bot?

valid niche
valid niche
#

also that on_message is a sort of tag system that works before a command is executed so ye

cloud dawn
#

ahhh that way of fit

zinc mural
#

@cloud dawn doesn't work

cloud dawn
zinc mural
#

it keep showing this

cloud dawn
#

Yeah but you only need to get the cwd

#

So ignore the error for now

zinc mural
cloud dawn
#

!d os.getcwd

unkempt canyonBOT
#

os.getcwd()```
Return a string representing the current working directory.
zinc mural
# cloud dawn !d os.getcwd
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

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

bot = commands.Bot(command_prefix=";")

@bot.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

print(os.getcwd())

client.run
#

like this?

cloud dawn
# zinc mural ```python import discord import os from discord import client from discord.ext i...
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

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

print(os.getcwd())
bot = commands.Bot(command_prefix=";")

@bot.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run
``` Before the error
zinc mural
# cloud dawn ```py import discord import os from discord import client from discord.ext impor...
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

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

bot = commands.Bot(command_prefix=";")

@bot.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

print(os.getcwd())

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run
#

so how

cloud dawn
#

This is also fine

zinc mural
cloud dawn
zinc mural
cloud dawn
#

The cwd

slate swan
#

what does your code print

zinc mural
#

did not print anything

#

it shows the same error

cloud dawn
#
import discord
import os
from discord import client
from discord.ext import commands
from discord.ext.commands import bot
from discord.flags import Intents

while True:
    print(os.getcwd())

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

print(os.getcwd())
bot = commands.Bot(command_prefix=";")

@bot.event
async def on_ready():
    print("The bot is ready!")

initial_extensions = []

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run
#

What does it spam?

zinc mural
cloud dawn
zinc mural
slate swan
#

you can manually declare a list of cogs and use them to load the extensions

cloud dawn
#

Who manually declares a list of cogs 😂

slate swan
#

lmao carl bot's owner did

#

the open source version

#
    def tempban(self,ctx, user: discord.Member,seconds):
        text = (seconds)
        in_seconds = {'h': 60 * 60, 'm': 60, 's': 1, ' ': 1}
        seconds = sum(int(num) * in_seconds[weight if weight else 's'] for num, weight in
                      re.findall(r'(\d+)\s?(m|s|h)?', text))
        current_time = datetime.datetime.now()
        final_time = current_time + datetime.timedelta(seconds=seconds)
        tempbanned = {"user_id": user.id, "BannedUntil": final_time}
        self.coll.insert_one(tempbanned)

This is how I defined my tempban

on_member_join
    await self.tempban(user.id,bannedday)
TypeError: tempban() missing 1 required positional argument: 'seconds'

However I get this error when I user joins

        now = datetime.utcnow()
        age = now - user.created_at
        days = age.days
        banday = (14 - days)
        bannedday = (banday*24*60*60)

Thats how bannedday is defined

formal portal
#

Hello

#

how do i ping users using bot

slate swan
unkempt canyonBOT
#

property mention: str```
Returns a string that allows you to mention the given user.
slate swan
#

or discord.Member.mention

cloud dawn
slate swan
slate swan
silk epoch
#

hello how to solve?

slate swan
slate swan
silk epoch
zinc mural
#

@cloud dawn what to do now

silk epoch
formal portal
cloud dawn
slate swan
#

@silk epoch

#

hey guys, so im making a verificaton bot and it creates the reaction but for some reason its not giving me any roles this is my code

#
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['message_id'] == payload.message_id:
                    role = discord.utils.get(bot.get_guild(payload.guild_id).roles, id=x['role_id'])
                    await bot.get_guild(payload.guild_id).get_member(paylod.user_id).remove_roles(role)

@bot.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['message_id'] == payload.message_id:
                    role = discord.utils.get(bot.get_guild(payload.guild_id).roles, id=x['role_id'])
                    await payload.member.add_roles(role)```
#
@commands.has_role('👑CEO👑')
async def reactrole (ctx, emoji, role : discord.Role, *, message):
    embed = discord.Embed(description = message)
    msg = await ctx.channel.send(embed = embed)
    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)```
#

im not getting any error code either

thin valley
#
async def hug(self, ctx):
    await self.bot.say("hugs {}".format(ctx.message.author.mention()))

An example @formal portal. member.mention() should be pinging someone once sent.

waxen granite
#
        lyrics_embed = discord.Embed(title=f"{song.title} - Lyrics",
            description=song.lyrics, color=discord.Colour.random())
        lyrics_embed.set_thumbnail(url=song.song_art_image_thumbnail_url)
        lyrics_embed.set_footer( 
            icon_url=self.bot.user.avatar_url, text="Lyrics from Genius API.")
        await ctx.send(embed=lyrics_embed)```
i want to split the song.lyrics to overcome the character limit. help pls
thin valley
#

context

silk epoch
thin valley
silk epoch
thin valley
formal portal
slate swan
#

if anyone is pretty good at reaction roles can u dm me because i need help with my verification bot

waxen granite
thin valley
slate swan
thin valley
cloud dawn
silk epoch
#

my token is valid.

cloud dawn
thin valley
cloud dawn
slate swan
#

pip install discord

silk epoch
cloud dawn
#

py -m pip install discord.py

slate swan
#

Uh Mass dm? Tos alert- I am not helping WalkAway

silk epoch
slate swan
valid niche
slate swan
waxen granite
#

where can i have a look to paginate?

slate swan
#

if anyone is pretty good at reaction roles can u dm me because i need help with my verification bot

#

im not getting an error code

silk epoch
#

I just regenerate :/

valid niche
unkempt canyonBOT
slate swan
#

just wont give me role

silk epoch
valid niche
slate swan
#

is ur json set up correctly

valid niche
#

if you click regenerate that means it made a new token and the old token is invalid

slate swan
#

does no one here know how to do reaction roles?

slate swan
unkempt canyonBOT
valid niche
#

then just look in a database for what emoji role and message etc

slate swan
#

Wait no thats not right

tawdry perch
slate swan
#

thats my code there

#

i get no error but i also get no role

slate swan
cloud dawn
valid niche
slate swan
#

@waxen granite Do rtfm paginator in dpy server

formal portal