#discord-bots

1 messages · Page 556 of 1

valid niche
#

could you show me your current json file?

slate swan
#

Could someone help?

slate swan
tawdry perch
#

@slate swan calling me a "dick" because I don't help via dms. but why..?

cloud dawn
#

You can also just do ctx.author.mention and it's without the ()

cloud dawn
fiery dagger
#

I need some help, im trying to make it so that my bot replies to a message if it contains a certain word, and since there's a lot of words i want it to reply to, I thought of making a list so I dont have to copy paste and slightly modify the same 2 lines of code over and over again, but it just gives me this error
TypeError: 'in <string>' requires string as left operand, not list

tawdry perch
#

ehh no it was more likely a question to them t

valid niche
rare saddle
#

Why a mistake?

tawdry perch
#

Also they can't really do anything to DMs things so I just report them to discord itself

slate swan
cloud dawn
valid niche
#

but a full name

hasty iron
slate swan
cloud dawn
hasty iron
#

what

#

in the if? what changes?

fiery dagger
#

huh

cloud dawn
fiery dagger
#

wait so do i just gotta take out the list entirely

#

as in I cant use it

valid niche
safe temple
#
Ignoring exception in command withdraw:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 171, in wrapped
    ret = await coro(*args, **kwargs)
  File "", line 44, in withdraw
    bal = await updatebank(ctx.author,0,"wallet")
  File "", line 112, in updatebank
    users[str(user.id)][mode] += users
TypeError: unsupported operand type(s) for +=: 'int' and 'dict'

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 547, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 901, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 180, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'dict'

can anyone help?

hasty iron
valid niche
#

or did you let the command do it?

slate swan
valid niche
cloud dawn
slate swan
#

lol i hate dark mode for replit

safe temple
hasty iron
slate swan
#

yeah

slate swan
cloud dawn
unkempt canyonBOT
#

@cloud dawn :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
hasty iron
#

!e ```py
ret = [1, 2, 3] in 'If error'

unkempt canyonBOT
#

@hasty iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
cloud dawn
#

Thats what i mean.

hasty iron
#

???

rare saddle
#

Guys, why a mistake?

silk epoch
#

help??

hasty iron
#

missing self

sick birch
cloud dawn
sick birch
#

It also happens when you miss self

hasty iron
#

the if has nothing to do with the error

safe temple
cloud dawn
#

So what? You are deliberately making something more confusing than needed.

sick birch
edgy meadow
silk epoch
#

how to fix ?

safe temple
# edgy meadow What was the problem?
Ignoring exception in command withdraw:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 171, in wrapped
    ret = await coro(*args, **kwargs)
  File "", line 44, in withdraw
    bal = await updatebank(ctx.author,0,"wallet")
  File "", line 112, in updatebank
    users[str(user.id)][mode] += users
TypeError: unsupported operand type(s) for +=: 'int' and 'dict'

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/bot_base.py", line 547, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 901, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/disnake/ext/commands/core.py", line 180, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'dict'

slate swan
#

Waiting for some help

sick birch
sick birch
#

Maybe you’re looking for discord.Activity

silk epoch
#

how?

safe temple
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

valid niche
#

@slate swan i see a few things odd about your code. You're for instance storing both the role name and role id. Also you are doing bot.get_guild(id).get_member(id), but you can just do payload.member to get the member.

valid niche
#

you also already have the role ID, so why not do member.guild.get_role(id)?

rare saddle
edgy meadow
safe temple
#

alright

valid niche
cloud dawn
#

You are missing seconds the user id is ctx and user is the bannedday

#

You are looking for this..

#

!d discord.ext.commands.Bot.invoke

unkempt canyonBOT
#

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

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.
coral vessel
#

i use this as welcome bot, the script running fine with no error but i tried joined as new member but did't work

@bot.event
async def on_member_join(member):
channel = bot.get_channel(channel id)
embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
await channel.send(embed=embed)

sick birch
#

You can’t have spaces in variable names (unless it’s pseudo code)

#

Also your indents seem to be messed up

#

That’s probably why it’s not working

cloud dawn
#

And

sick birch
#

Unless that’s just my mobile formatting

cloud dawn
#

!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.

cloud dawn
sick birch
#

Oof alright

#

Looks unindented on my screen haha

cloud dawn
#

Turn it horizontally

safe temple
sick birch
#

I’ll take your word for it that’s in indented lmao

cloud dawn
sick birch
#

Other than that I don’t see what’s wrong

safe temple
cloud dawn
# safe temple huh

That is the amount of times i've seen people use this half working code.

safe temple
#

it was from a tutorial

cloud dawn
#

I know.

safe temple
#

yeah

#

and do you know what is wrong with it?

cloud dawn
#

Doesn't mean it's good though.

sick birch
#

Oh it’s one of those “discord bot economy tutorials”

#

Explains the client variable and the json

cloud dawn
#

But anyways here is the issue users[str(user.id)][mode] += users

sick birch
#

(Strongly recommend against json as a db)

cloud dawn
#

users is a dict so you can't just append it to an int

safe temple
sick birch
cloud dawn
sick birch
#

Plenty of options

#

Make sure it’s relational though

cloud dawn
#

postgrepy_strong

#

And async

sick birch
#

agreed

#

Yeah an async driver for said database

#

I.e aiosqlite, asyncpg

cloud dawn
#
thin valley
#

Someone Ping me?

cloud dawn
sick birch
#

Using an actual database will save you headache down the line when your json database breaks and you lose all your data

cloud dawn
#

The reply auto pings

thin valley
#

I wrote something stupid, I wanted to ask did someone ping me? Because I got a ping in here

sick birch
#

You misunderstood each other

cloud dawn
slate swan
#

big problem

#

if you don't know how to formulate questions

#

big problem it is

thin valley
#

Someone interrupted me while I was formulating that question. I just pressed enter after writing that without checking 🤷‍♂️

slate swan
cloud dawn
slate swan
boreal ravine
slate swan
#

wdym, that's my keyboard

steady flume
#

how do I get a mention of all the roles of a certain participant ?

slate swan
#

Participant ?

steady flume
#

member*

slate swan
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
slate swan
#

Returns a list of roles object

steady flume
#

i neednt in list

slate swan
#

You get a list of all roles

#

Just loop through it

steady flume
#

okay

#

ty

slate swan
#
wallet_path = "./data/economy/wallet.json"

with open(wallet_path, "r") as f:
    wallet = json.load(f)
wallet = wallet[str(ctx.author.id)][str(ctx.guild.id)]
``` ```json
{
  "893759198297473034": {
    "891338782534676520": "1000"
  }
}
#

Error: Command raised an exception: AttributeError: 'str' object has no attribute 'id'

#

:')

full mural
#

Oh ok had no response for a bit so came here

slate swan
#

People will get to you

safe temple
#

wait

#

nevermind

slate swan
#

:/

safe temple
#

wait

#

shouldnt the 1000 be a int

#

not a string

#

you should remove the " around 1000

#

but im not sure if that will fix your issue

slate swan
#

the error msg is still AttributeError: 'str' object has no attribute 'id' xD

safe temple
#

wallet = wallet[int(ctx.author.id)][str(ctx.guild.id)]
#

try that i guess

slate swan
#

wtf

#

guys, How to make a bot ignore certain channels?

#

why int authors id?

safe temple
#

bruh idk im just guessing at this point

slate swan
#

Yes

slate swan
#

guys, How to make a bot ignore certain channels?

thin valley
#

Depends on what you want to do and what your code looks like.

#

Could you please give us an insight?

lament mesa
sick birch
#

Check the channel, return

slate swan
#

who here knows how to do a giveaway bpt

#

it works the reroll doesnt tho

thin valley
# slate swan guys, How to make a bot ignore certain channels?

You have to have a predefined channelID and before the bot does anything he loops through the channelID's (or looks at only one (if there is only one)) and checks if they are the current channelID in an if statement. If they are or are not he operates on behalf of them.

boreal ravine
#

hm

thin valley
#

Doesn't need to be a on_message event

sick birch
thin valley
#

it depends on what tommy here wants to do

thin valley
sick birch
#

They just don’t want commands to run in certain channels

#

You can accomplish this in 3 lines

thin valley
#

Well I do not know what the user wants because he hasn't said anything.

sick birch
#

From what they said I assume they don’t want commands to be run in certain channels

thin valley
#

Well just have a Blacklist of channels.

sick birch
#

Yeah and on message check if the channel id is in the black list

safe temple
thin valley
#

No, you don't need to on_message check.

sick birch
#

That’s up to the user

sick birch
thin valley
#

Let's say

manic wing
#

@hasty iron can you help me pwease 😇

hasty iron
#

what

manic wing
# hasty iron what
Traceback (most recent call last):
  File "/home/caeden/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
TypeError: object NoneType can't be used in 'await' expression

```have you seen this before?
#

I swear I'm not doing anything wrong

hasty iron
#

coro(*args, **kwargs) returned None

thin valley
#

The person wants to send a message in a channel. They will fetch the channelID that the command was put in (or the owner has already put it as an arg*). Then the bot will loop through a blacklist and see if the channelID is equal to any other channelID in the blacklist. If not, they will just send something. If it is, they wont.

hasty iron
#

oh

thin valley
#

@sick birch

manic wing
#

my code is flawless

hasty iron
#

send your code

thin valley
#

You don't need a on_message event for that. It can be a simple command.

sick birch
#

Hmm

manic wing
#

@hasty iron don't judge the code, i literally made it 20 min ago

sick birch
#

No need for a loop btw

hasty iron
#

on_ready is sync

thin valley
sick birch
#

You can just do something like if channel.id in blacklisted_channels

hasty iron
#

it needs to be an async function

manic wing
#

oh ffs

hasty iron
#

line 15

manic wing
#

you're right, ty

thin valley
sick birch
#

Yeah both works but personally I think the on message would be easier

slate swan
#

Heyyyy can someone help me with my giveaway bot

sick birch
#

Lmao the guy who asked the question is gone

slate swan
#

been asking for a long time now

thin valley
#

It really just depends on the command

sick birch
thin valley
#

But please name your problem

slate swan
#

so my giveaway bot

sick birch
#

We’re not gonna make your bot for you but we can assist with errors or issues

slate swan
#

it works but reroll doesnt

sick birch
#

Okay define it doesn’t work

slate swan
#

want me to send the code

thin valley
#

Please send a Error and a Code @slate swan

sick birch
#

Along with any errors

slate swan
#

ok 2 secs

thin valley
#

Ok.

slate swan
#
@commands.has_role('👑CEO👑')
async def giveaway(ctx):
    await ctx.send("Lets start with this giveaway! Answer these questions within 15 seconds! ")
    questions = ["Which channel should it be hosted in? ",
                            "What should be the duration of the giveaway?  (s|m|h|d)",
                            "What is the prize of the giveaway?"]
    answers = []
    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel
    for i in questions:
        await ctx.send(i)
        try:
            msg = await bot.wait_for('message', timeout = 15.0, check = check)
        except asyncio.TimeoutError:
            await ctx.send('You didn\'t answer in time, please be quicker next time!')
            return
        else:
            answers.append(msg.content)
    try:
        c_id = int(answers[0][2:-1])
    except:
        await ctx.send(f"You didnt mention a channel properly. Do it like this {ctx.channel.mention} next time.")
    channel = bot.get_channel(c_id)
    time = convert(answers[1])
    if time == -1:
        await ctx.send(f"You didn't answer the time with a proper unit. Use (s|m|h|d) next time!")
        return
    elif time == -2:
        await ctx.send(f"The time must be an integer. Please enter an integer next time.")
        return
    await ctx.send(f"The giveaway will be in {channel.mention} and will last {answers[1]} seconds!")
    embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = 0xA5FF1C)
    embed.add_field(name = "Hosted by: ", value = ctx.author.mention)
    embed.set_footer(text = f"Ends {answers[1]} from now on!")
    my_msg = await channel.send(embed=embed)
    await my_msg.add_reaction("🎉")
    await asyncio.sleep(time)
    new_msg = await channel.fetch_message(my_msg.id)
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won {prize}")

@bot.command()
@commands.has_role('👑CEO👑')
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
    try:
        new_msg = await channel.fetch_message(id_)
    except:
        await ctx.send("The id was entered incorrectly.")
        return
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won {prize}!")```
#

says prize isnt defined when i reroll

sick birch
#

Full traceback please

slate swan
#

what

thin valley
#

Well you have never defined "prize"

safe temple
#

error

thin valley
slate swan
#

its defined in the top command but not the second how would i link them

thin valley
#

Global the Variable.

slate swan
#

so it says the same prize

thin valley
#

Or simply use a Database.

safe temple
#

global or pass it through

slate swan
#

oh right

#

lemme test 2 secs

thin valley
#

Database in this case would be safer.

lament mesa
thin valley
#

Global it in the upper command, not the lower one. The one it's being defined it (just as info).

thin valley
#

Postgre is very good.

safe temple
#

ive been told to use a database

lament mesa
slate swan
#

how would i do it

safe temple
#

bc i was storing the bank functions inside of a json file

thin valley
lament mesa
#

!globals

unkempt canyonBOT
#

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

Instead of writing

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

do this instead

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

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

thin valley
#
global prize
manic wing
#

@hasty iron last question, ```py
Traceback (most recent call last):
File "/home/caeden/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/caeden/Jarvis/main.py", line 77, in on_message
output = ProcessMessage(message)
File "/home/caeden/Jarvis/main.py", line 41, in init
self.message = message
AttributeError: can't set attribute

why cant it set this;
```py
def __init__(self, message):
        self.message = message
        self.message = self.clean(self.message)
        self.tags = []
hasty iron
#

is the class slotted?

manic wing
#

no, im not subclassing

hasty iron
#

oh wait

#
    @property
    def message(self): ...
``` you have this
manic wing
#

fuck sake man you're so smart

hasty iron
#

you have to define a message.setter in order to do that

slate swan
thin valley
manic wing
safe temple
thin valley
#

you already defined prize = answers[2]

manic wing
#

thanks 😳

safe temple
#
prize = answers[2]```
thin valley
#

just global prize. Then the value "answers[2]" will be global.

slate swan
#

so i global it below the prize = answers[2]

thin valley
#

no

#

after the "def ..."

tired hill
#

+sonhos

thin valley
#

you place global prize

slate swan
#

on the reroll or the giveaway

thin valley
#

reroll

slate swan
#

i did this @bot.command() @commands.has_role('👑CEO👑') async def reroll(ctx, channel : discord.TextChannel, id_ : int): global prize try: new_msg = await channel.fetch_message(id_) except: await ctx.send("The id was entered incorrectly.") return users = await new_msg.reactions[0].users().flatten() users.pop(users.index(bot.user)) winner = random.choice(users) await channel.send(f"Congratulations! {winner.mention} won {prize}!")

#

and it says prize isnt defined

#

wait no it says roll is not defined

lament mesa
#

Send the full traceback

slate swan
#

wdym

safe temple
#

the full error

slate swan
#

i wrote reroll

#

not roll

#

i just tried to reroll again and it now says prize isnt defined

#
@commands.has_role('👑CEO👑')
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
    global prize
    try:
        new_msg = await channel.fetch_message(id_)
    except:
        await ctx.send("The id was entered incorrectly.")
        return
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(bot.user))
    winner = random.choice(users)
    await channel.send(f"Congratulations! {winner.mention} won {prize}!")```
#

even tho it is

tawdry perch
#

Did you define it somewhere else than global?

valid niche
slate swan
safe temple
#

into the function?

#

wait nevermind

valid niche
unkempt canyonBOT
#

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

Instead of writing

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

do this instead

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

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

valid niche
#

also let me see if i can find that attribute thing

slate swan
#

what?

lament mesa
#

Use something immutable like a dictionary instead of globals

valid niche
#

!botvar

unkempt canyonBOT
#

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

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

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

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

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

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

valid niche
#

that was it

#

@slate swan

slate swan
#

wha

#

what is that

valid niche
#

read that

#

and use that instead of global

#

it's more readable, and works across cogs

slate swan
#

thats just a variable?

maiden fable
cloud dawn
#

Or just use OOP

slate swan
#

tf is OOP

#

👏

lament mesa
#

Object oriented programming

#

It's all objects™️

tawdry perch
#

Objects everywhere

safe temple
#

™️

#

OOP™️

slate swan
#

"I personally use discord.Member everywhere in my code because I don't know how to work with the docs"

maiden fable
#

Lmao what the

tawdry perch
#

?

slate swan
#
@bot.command()
async def ban(ctx, member):
    await discord.Member.ban()
tawdry perch
#

That would not work, does it pithink

slate swan
tawdry perch
#

Make it ban the author of message

patent surge
#

Why bot.get_user() is not working ?

slate swan
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
slate swan
#

hm

tawdry perch
#

and add it as command that anyone can run

patent surge
lament mesa
#

Maybe the user isn't cached

patent surge
#

I am giving my own Id

#

but still returns None

#

???

lament mesa
#

Maybe the bot isn't ready

#

!d discord.Client.wait_until_ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.
slate swan
#

why not get_member

tawdry perch
#

How do you ban a user not in guild?

#

Someone in this server wanted to setup my discord bot from github and they told me that they don't code at all. They just copy paste everything and run it.

#

It is pain to try help them get it working

hasty iron
patent surge
#

after that i do

maiden fable
dapper cobalt
slate swan
#

how do I make two commands with different name inside the same cog file

fading kiln
#

Hello

#

How to learn discord python

#

effectively

hasty iron
patent surge
slate swan
hasty iron
#

no, you need a function

slate swan
#

really

#

aliases=["user_info", "member", "member_info", "u"])

#

what does this do in the command decorator

hasty iron
#

make aliases for the command?

slate swan
#

ya

#

what does aliases do

patent surge
#

aliases == nickname

slate swan
#

so

hasty iron
#

google the definition of an "alias"

slate swan
#

if i do

@command.commands(name="user", aliases=["user_info", "member", "member_info", "u"])

i can run that command with !user_info right?

patent surge
#

Yes

slate swan
#

ah I see

#

I also heard

#

you can make a help command, by defining something in these decorators using cogs

hasty iron
#

no, you cannot, you can add descriptions and stuff like that but you cant make a whole help command from them you'll need an actual implementation

slate swan
#

ya its the description I mean

lunar helm
#
    if plus:
        for i in range(level):
            try:
                role = get(user.guild.roles, id=roles[str(i+1)])
                await user.add_roles(role, reason="leveled up", atomic=False)
            except KeyError:
                print("no role")
            try:
                role = get(user.guild.roles, id=roles[str(i)])
                await user.remove_roles(role, reason="leveled up", atomic=False)
            except KeyError:
                print(y + "roles")
                print("no role to remove")``` why does it make a never ending loop?
#

like it's not spamming forever

#

but it never continues past this part of code

#

if i remove python try: role = get(user.guild.roles, id=roles[str(i)]) await user.remove_roles(role, reason="leveled up", atomic=False) except KeyError: print(y + "roles") print("no role to remove") it works

#

im trying to make it so if i level up to 10 for example

#

level 5 role is removed

#

because roles are different per server it just checks if there is a role for each level

#
{
  "5": 901614930879455252,
  "10": 901626195379109928
}```
dapper cobalt
unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

shy junco
#

How do I check the count for each reaction on a message? Like if I have a message with reactions from 1️⃣ - 9️⃣ , how do I check the amount of votes for each reaction

slate swan
#
import discord
from discord.ext import commands


class Information(commands.Cog):
    """A cog with commands for generating embeds with server info, such as server stats and user info."""

    def __init__(self,  bot: Bot):
        self.bot = bot

    @commands.command(name="server", aliases=["server_info", "guild", "guild_info"]):
    async def server_info(self, ctx: Context) -> None:
        await ctx.send("test")


def setup(bot: Bot) -> None:
    """Load the Information cog."""
    bot.add_cog(Information(bot))

How come my typehints for bot and ctx throws me an error

#

bot : commands.Bot

#

since you didnt imported Bot from discord.ext.commands

#

ah and how would I import it

#
    def tempban(self, 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.utcnow()
        final_time = current_time + timedelta(seconds=seconds)
        tempbanned = {"user_id": user, "BannedUntil": final_time}
        self.coll.insert_one(tempbanned)

I am defining tempban here

    @commands.Cog.listener()
    async def on_member_join(self, user: discord.Member):
        now = datetime.utcnow()
        age = now - user.created_at
        days = age.days
        banday = (14 - days)
        bannedday = str(banday*24*60*60)

        if days == 0:
            await user.ban(reason="Alt")
            channel = self.bot.get_channel(676931619294281729)
            await channel.send(f"Auto Banned {user} `{user.id}` for being an ALT")

        elif days < 14:
            self.tempban(user, bannedday)
            await user.ban(reason="Your account is too new! Feel free to join back when your account is atleast 15 days old. discord.gg/")
            channel = self.bot.get_channel(676931619294281729)
            await channel.send(f"Auto banned {user} `{user.id}` for being younger than 14d. Come back in {banday} days")
``` And then doing this to add a document however the user is banned but no document is added when the user is older than 1 day but younger than 14

this is pymongo btw
#

!d discord.ext.commands.Bot get some idea

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
fiery dagger
#

if message.content.lower() in list:
await message.channel.send(list1)

only works if the message is just the word from the first list, how do I make it so it works even if there's other words in the message?

slate swan
#

check it the other way

#

oop

fiery dagger
#

if list in message.content.lower(): ?

#

cus that doesn't really work

kindred epoch
#

ye

#

what

dapper cobalt
forest blade
#

if any(message.content.lower().split() in list):

fiery dagger
# kindred epoch what

I actually had some issues with that stuff earlier since I had it like that and it kept giving me this error TypeError: 'in <string>' requires string as left operand, not list.

#

thanks for the help

slate swan
#

!u

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

slate swan
#

Hey, does anyone know how to make buttons unavaliable?

Like this:

#

Like if you click on it, it should become unavaliable

#

grayed out... however you wanna say

kindred epoch
slate swan
#

discord-py-slash-command

kindred epoch
#

do they have docs?

slate swan
#

Yes but

#

I havent found it anywhere in the docs

kindred epoch
#

send their github

slate swan
#

Kk one second

#

HOLD UP that is actually smart!

#

Should be this

#

Yes it is this

indigo forum
tawdry perch
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.

tawdry perch
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

indigo forum
#

ok

agile mango
#

yo, any1 knows how to create a channel nuke on discord.py and if so, can you explain to me how does it work. I'm new to discord.py

indigo forum
indigo forum
agile mango
#

in the way to clear all messages from a channel

slate swan
agile mango
#

i mean, do $nuke and it deletes the channel and creates another and it's like if it cleared all msgs instantly

edgy meadow
#

you could also use purge to remove messages

slate swan
edgy meadow
#

True, whatever ways fits the most

steep estuary
#

is searching for messages in servers against terms ?

slate swan
#

Hey guys so im trying to make a thing so if write >ping in any channel its says Pong in 1 specific channel i tried this code but for some reason its not working

#
async def Ping(ctx):
    channel = bot.get_channel(CHANNEL ID HERE)
    await channel.send("Pong")```
#

can someone help?

#

theres no error code

#

it just doesnt send to the channel id i entered

boreal ravine
#

@slate swan y pass context

#

stop copying code

#

and ur command is >Ping

#

not >ping

#

do u read ur own functions?? 😂

slate swan
#

just didnt send with a capital in this server

#

and im not copying code

#

its litterally 4 lines

final iron
#

Why are you passing context

boreal ravine
#

^

boreal ravine
slate swan
#

guild.get_channel?

boreal ravine
#

yes

slate swan
#
# BALANCE --------------------------------------------------------------------------------------- Fortu'Neko#2987 --
@commands.command(aliases=["bal", "money"])
async def balance(self, ctx, member: discord.Member = "this"):

    if member == "this":

        with open(wallet_path, "r") as f:
            wallet = json.load(f)
        wallet = wallet[str(member.id)][str(ctx.guild.id)]

        with open(bank_path, "r") as f:
            bank = json.load(f)
        bank = bank[str(member.id)][str(ctx.guild.id)]

        a = discord.Embed(description=f"{member.mention}'s currently balance check!",
                          color=col)

        a.set_author(name=f"{self.client.user.name}",
                     icon_url=self.client.user.avatar_url,
                     url=inv)

        a.add_field(name=f"Wallet",
                    value=f"{wallet}",
                    inline=False)

        a.add_field(name=f"Bank",
                    value=f"{bank}",
                    inline=False)

        await ctx.send(embed=a)

    else:

        with open(wallet_path, "r") as f:
            wallet = json.load(f)
        wallet = wallet[str(ctx.author.id)][str(ctx.guild.id)]

        with open(bank_path, "r") as f:
            bank = json.load(f)
        bank = bank[str(ctx.author.id)][str(ctx.guild.id)]

        b = discord.Embed(description=f"{ctx.author.mention}'s currently balance check!",
                          color=col)

        b.set_author(name=f"{self.client.user.name}",
                     icon_url=self.client.user.avatar_url,
                     url=inv)

        b.add_field(name=f"Wallet",
                    value=f"{wallet}",
                    inline=False)

        b.add_field(name=f"Bank",
                    value=f"{bank}",
                    inline=False)

        await ctx.send(embed=b)
``` `-bal @` works but `-bal` not
#
async def Ping(ctx):
    channel = guild.get_channel(899011791605084161)
    await channel.send("Pong")```
#

still dont work

#
@bot.command()
async def Ping(ctx):
    await ctx.send("Pong")
#

ctx is authors channel

#

or you want to send in a spec channel?

#

no im trying to make the pong send to 1 specific channel

slate swan
#
    @staticmethod
    def join_role_stats(role_ids: list[int], guild: Guild, name: Optional[str] = None) -> dict[str, int]:
        """Return a dictionary with the number of `members` of each role given, and the `name` for this joined group."""
        member_count = 0
        for role_id in role_ids:
            if (role := guild.get_role(role_id)) is not None:
                member_count += len(role.members)
            else:
                raise NonExistentRoleError(role_id)
        return {name or role.name.title(): member_count}
                         ^

Why do I get a add global statement warning here?

slate swan
#
@bot.command()
async def ping(ctx):
    channel = guild.get_channel("id")
    await channel.send(f"Pong!")

#

any1 help me?

slate swan
#

" id "

#

" you've to use

#

"

#

wait

#

but if im entering the channel id into the code if i use speach marks it makes it a string no?

#

youve to put it in a string xD

#

your id

#

f"" is replaycing the .format... thing

#
async def Ping(ctx):
    channel = guild.get_channel("899011791605084161")
    await channel.send(f"Pong")```
#

That dont work

#

replayce guild to client

#

oh

#

well not for me but yh

#

2 secs

#

bot

#

xD

#

I'm using self.client.-

#
async def Ping(ctx):
    channel = bot.get_channel("899011791605084161")
    await channel.send(f"Pong")```
#

still nothing

#

._.

slow fog
#

what do you need

slate swan
#

i wanna make it so i can say >Ping anywhere in my server and it says Pong in 1 specific channel

#

y'all got any good and cool command ideas? i kinda need some since i suck in terms of imagination

#
 @bot.command()
async def Ping(ctx):
    await channel.send(f"Pong")```
slate swan
#

dont have to be a channel id if u put a channel id its gon send to one

stiff nexus
#
if embed_footer.strip().lower() == "none":
    embed_footer = discord.Embed.Empty
```what will this do?
slate swan
#

How would I get all roles ID in a guild and store it in a list?

slate swan
#

if the if returns True

slate swan
slate swan
slate swan
slate swan
#

use a for loop and loop over a guild's roles, the property name is roles

#

i ain't gonna spoonfeed ya

stiff nexus
slate swan
#

basic python

#

never asked for spoonfeed

#

im new to the library

slate swan
stiff nexus
#

ok

slate swan
#
        for role in guild.roles:
            return role.id

does role have an attribute called id in this case?

slate swan
slate swan
#

thanks for the help love this channel 🙂

#

alright so now I've got to add it to a list

slate swan
slate swan
slate swan
#

just be patient

slate swan
#

@slate swan can u help me w sum

#

?

slate swan
slate swan
#
role_ids = []
        for role in guild.roles:
            role_ids.append(role.id)

role_ids would be ["id", "id", "id", "etc.."] right?

slate swan
slate swan
#

ok ty

#

is mutedRole None?

#

print mutedRole and see what that prints

slate swan
boreal ravine
#

ah a response

slate swan
#

do you have an on_message event in your code

#
@bot.event
async def on_message(message):
    if message.content == "hi":
        await message.channel.send("hello")```
#

that's why

boreal ravine
#

oh use .listen()

slate swan
#

instead of .event use .listen()

boreal ravine
slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

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

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

Example...
slate swan
slate swan
boreal ravine
#

he used a string as an example though

#

😫

slate swan
slate swan
slate swan
boreal ravine
boreal ravine
#

😂

slate swan
#

mhm

#

pylance?

boreal ravine
#

Aren't warnings usually for modules

slate swan
#

No I legit have a warning on that

#

weird

#

man

boreal ravine
#

what

dawn lion
#

How to can a get user nickname?

#

How to can a get user nickname?

reef shell
unkempt canyonBOT
#

property display_name: str```
Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
slate swan
reef shell
#

wdym

slate swan
#

unmutes all the muted mmembers

#

@bot.command(aliases=['massunmute'])
@commands.has_permissions(manage_messages = True)
async def unsilentall(ctx,member : discord.Member):
    mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
    await member.remove_roles(mutedRole) 
    await ctx.send('All members have been unmuted!')```
reef shell
#

Loop through the muted role members and remove their roles

#

!d discord.Role.members

unkempt canyonBOT
reef shell
#

You might use asyncio.sleep() or else your bot will be ratelimited

slate swan
#

ight

pliant gulch
#

Just clone the role, remove it then add it back

slate swan
pliant gulch
#

Ratelimits are dynamic

dawn lion
#

@reef shell

#
@commands.command()
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def cat(self, ctx):
        nick_of_old = ctx.author.display_name
        print(nick_of_old)
        nick_of_new = 'ᓚᘏᗢ ' + str(nick_of_old)
reef shell
#

yes, mass removing roles will ratelimit you anyways

dawn lion
#

nick_of_old is NoneType

leaden jasper
#

how to get message id from ctx?

#
<class 'discord.ext.commands.context.Context'>```
#
AttributeError: 'Context' object has no attribute 'id'
slate swan
#

and as you know, a Message instance has an id property

leaden jasper
#

is it message or Message?

dawn lion
#

@reef shell

#
@commands.command()
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def cat(self, ctx):
        nick_of_old = ctx.author.display_name
        print(nick_of_old)
        nick_of_new = 'ᓚᘏᗢ ' + str(nick_of_old)
reef shell
#

Yes?

dawn lion
#

nick_of_old is NoneType

slate swan
leaden jasper
#

wtf

#

some stuff are case sensitive

#

im just asking is it or not

slate swan
#

there's a difference between properties and classes

reef shell
dawn lion
#

no

#

!d intents

unkempt canyonBOT
leaden jasper
#

so ur not going to tell me?

reef shell
#

Try after turning it on both in your code and developer portal

slate swan
reef shell
#

even though it should work fine without that intent

leaden jasper
#

god ur so stupid

reef shell
#

discord.Message is a class

slate swan
dawn lion
reef shell
dawn lion
#
import discord
from discord.ext import commands

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

class U(commands.Cog):

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

    @commands.command()
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def cat(self, ctx):
        nick_of_old = ctx.author.display_name
        print(nick_of_old)
        nick_of_new = 'ᓚᘏᗢ ' + str(nick_of_old)

        await ctx.author.edit(nick=nick_of_new)

def setup(client):
    client.add_cog(U(client))

Error:

C:\Users\Савелий\AppData\Local\Programs\Python\Python38\python.exe C:/Users/Савелий/Desktop/Glidingtheo/main.py
Traceback (most recent call last):
  File "C:\Users\Савелий\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\Савелий\Desktop\Glidingtheo\cogs\fan.py", line 5, in <module>
    intents.member = True
AttributeError: 'Intents' object has no attribute 'member'

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

Traceback (most recent call last):
  File "C:/Users/Савелий/Desktop/Glidingtheo/main.py", line 50, in <module>
    client.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\Савелий\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Савелий\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fan' raised an error: AttributeError: 'Intents' object has no attribute 'member'

Process finished with exit code 1
reef shell
#

members

#

Not member*
And you must pass that intent instance when making your bot instance
Not in a cog

rain rose
#

hey, i have a problem:

i need to make a command that sets a variable to a channel, executed by a command.

like /setchannel or something, that sets the channel to a variable, so i can make the output of the bot, go to the set channel.

please @ me if you can help.

proper inlet
#

or just get the channel for the command?

slate swan
#
@commands.command(aliases=["bal", "money"])
    async def balance(self, ctx, member: discord.Member = "here"):

        if member == "here":

            with open(wallet_path, "r") as f:
                wallet = json.load(f)
            wallet = wallet[str(member.id)][str(ctx.guild.id)]

            with open(bank_path, "r") as f:
                bank = json.load(f)
            bank = bank[str(member.id)][str(ctx.guild.id)]

            a = discord.Embed(description=f"{member.mention}'s balance check!",
                              color=col)

            a.set_author(name=f"{self.client.user.name}",
                         icon_url=self.client.user.avatar_url,
                         url=inv)

            a.add_field(name=f"Wallet",
                        value=f"{wallet}",
                        inline=False)

            a.add_field(name=f"Bank",
                        value=f"{bank}",
                        inline=False)

            await ctx.send(embed=a)

        else:

            with open(wallet_path, "r") as f:
                wallet = json.load(f)
            wallet = wallet[str(ctx.author.id)][str(ctx.guild.id)]

            with open(bank_path, "r") as f:
                bank = json.load(f)
            bank = bank[str(ctx.author.id)][str(ctx.guild.id)]

            b = discord.Embed(description=f"{ctx.author.mention}'s balance check!",
                              color=col)

            b.set_author(name=f"{self.client.user.name}",
                         icon_url=self.client.user.avatar_url,
                         url=inv)

            b.add_field(name=f"Wallet",
                        value=f"{wallet}",
                        inline=False)

            b.add_field(name=f"Bank",
                        value=f"{bank}",
                        inline=False)

            await ctx.send(embed=b)
``` {prefix}bal @slate swan is working, but only {prefix}bal not, why...
proper inlet
# rain rose yes

if you want to store the channel you do it in a json file, I would recommend using a database like sqlite

rain rose
#

i need it to then be used in other commands.

proper inlet
rain rose
#

i think i will

#

but idk json.

proper inlet
#

you can get the mentioned the channel and store the channel id

rain rose
#

so this will be fun.

hasty iron
#

use mongodb if you want nosql

proper inlet
shy junco
#

how do i check if a bot reacted to a message

shy junco
rain rose
proper inlet
rain rose
slate swan
#

thx for nothing bth

shy junco
proper inlet
#

for small bots

proper inlet
#

but i still recommend using sql

shy junco
#

which database would you use for a public bot?

reef shell
#

sql is more like literal english language

proper inlet
novel apexBOT
#

This is not a Modmail thread.

proper inlet
#

opp

#

wrong server

proper inlet
proper inlet
# shy junco which database would you use for a public bot?

https://www.postgresql.org/ - Widely used, open source database with good data integrity and feature set. The typical recommendation for bots.
https://www.mysql.com/ - The de facto SQL standard in software development. Usually not recommended here due to the decreased feature set in comparison to PostgreSQL, but strongly time-tested.
https://www.sqlite.org/index.html - File-based DB, no authentication. Lack of networking means query-by-query time is relatively fast, but tends to chug past a certain amount of load.

#

i prefer postgres to mysql

reef shell
#

sql makes him cry

proper inlet
reef shell
#

Oh mb

stiff nexus
#

how do i make mt bot deafen itself???

proper inlet
slate swan
#

!d

unkempt canyonBOT
slate swan
#

!p

unkempt canyonBOT
#
Missing required argument

pep_number

shy junco
#

Does anyone know how to check if a bot reacted to a message

slate swan
#

!p fetch_invites()

unkempt canyonBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

shy junco
#

using the on_raw_reaction_add event

dense swallow
reef shell
#

Kindly

proper inlet
#

ya sqlite is better for smaller bots

slate swan
#

can any1 help me find fetch_invite()

dense swallow
reef shell
unkempt canyonBOT
#

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

Gets an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") from a discord.gg URL or ID.

Note

If the invite is for a guild you have not joined, the guild and channel attributes of the returned [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") will be [`PartialInviteGuild`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialInviteGuild "discord.PartialInviteGuild") and [`PartialInviteChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialInviteChannel "discord.PartialInviteChannel") respectively.
slate swan
#

tysm

proper inlet
dense swallow
#

I too said that.

slate swan
reef shell
#

!d discord.Invite.url

unkempt canyonBOT
slate swan
#

I don't understand

hasty iron
#

you pass in the invite URL

slate swan
#
py_invite = await self.bot.fetch_invite(constants.Guild.invite)
        online_presences = py_invite.approximate_presence_count
        offline_presences = py_invite.approximate_member_count - online_presences
        member_status = (
            f"{constants.Emojis.status_online} {online_presences:,} "
            f"{constants.Emojis.status_offline} {offline_presences:,}"
        )

as you see here, this code has constants.Guild.invite as their argument in fetch_invite, but I don't have the constants class so I don't understand what to write here

hasty iron
#

or code

#

a url like discord.gg/python

slate swan
#

but the url can vary on different servers the command is ran in

slate swan
#

so far it's been good and I've found a way and another to fix stuff, but I've never used fetch_invite so idk what I can do here

hasty iron
#

then constants should be defined

slate swan
#

constans is a class

#

and it has like, 1000 lines

hasty iron
#

yeah

#

whats the issue

slate swan
#

and they import, from other files, that also has 1000 lines

#

I wont use constants

hasty iron
#

then dont use it?

slate swan
#

i wont? my question is how can I use fetch_invite in this case?

hasty iron
#

chess

slate swan
hasty iron
unkempt canyonBOT
#

class discord.TextChannel```
Represents a Discord guild text channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
reef shell
#

It has a method called create_invite or smthng like that

slate swan
slate swan
#

and its only one argument I need to pass right

#

in fetch_invite

reef shell
reef shell
#

Oh god

#

!d discord.ext.commands.Context.channel

unkempt canyonBOT
slate swan
#

how does this involve with fetch_invite, that's what im not understanding

reef shell
#

Are you using a this code inside a command's function?

slate swan
#

yes

reef shell
#

You do know that context is passed in command functions, don't you?

slate swan
#

yes

reef shell
#

So, i hope you understand how to get the TextChannel from context and then create an invite using TextChannel.create_invite()

#

That's what you asked for

slate swan
#

ahhhh

#
inv_url = ctx.channel.create_invite()
        g_invite = await self.bot.fetch_invite(inv_url)
#

so this would work

reef shell
#

It's a coro.

#

You need to await it

slate swan
#

ahh

coral vessel
#

Need help so i write code like this for dm welcome message
bot = commands.Bot(command_prefix = '!', intents=intents)

its work perfect but why my commad with "!" die how i can fix this ?
if i remove intents=intents dm message did't work.

reef shell
#

did you define that intents var?

coral vessel
#

How i can do that?

dense swallow
#

he asked if u could send what those intents variable is

slate swan
#
    @tasks.loop(seconds=600)
    async def checker(self):
        try:
            fetchall = self.coll.find({})  # return all documents inside the db
            print("Hello!")
            current_time = datetime.utcnow()
            async for x in fetchall:
                if current_time >= x["BannedUntil"]:  # do stuff after this
                    unbanuser = x["user_id"]
                    member = discord.Object(id={unbanuser})
                    guild = self.bot.get_guild(int)
                    await guild.unban(member, reason="Tempban for new account expired.")
                    await self.coll.delete_one(unbanuser)

        except Exception:
            pass

Why wont my task start? It doesnt print anything either
My innit

class newcomers(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.coll = bot.plugin_db.get_partition(self)
        self.checker.start()
valid perch
#

Well likely it's throwing an error. And because you do nothing if an error happens it acts like it

#

I'd recommend raising the error

velvet crest
#

is there a way i can set a max ram usage fro my bot hosted on my pc ?

haughty quartz
brave vessel
#

But, it won't start and it's erroring because you shouldn't start a task in __init__

#

the bot won't be ready yet, you should start it in on_ready

#

so add a listener like

@commands.Cog.listener()
async def on_ready(self):
  if not self.checker.is_running():
    self.checker.start()
slate swan
#
created = embed.timestamp(ctx.guild.created_at)

        embed.description = (
            f"Created: {created}"
            f"\nVoice region: {region.title()}"
            f"{features}"
            f"\nRoles: {num_roles}"
            f"\nMember status: {member_status}"
        )

why I get an error saying created is empty?

#

@kindred epoch havent found something?

#

argh

#

Does anyone know how to make an embed appear like this?

discord-py-slash-command

final iron
#

Those are buttons

slate swan
#

How do I go about logging the use of commands in a specific channel?

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
boreal ravine
haughty quartz
boreal ravine
#

@brave vessel @slate swan whats that symbol on your name for?

unkempt canyonBOT
boreal ravine
brave vessel
#

Honestly no purpose lol

slate swan
#

@boreal ravine```
created = embed.timestamp(ctx.guild.created_at())
TypeError: 'datetime.datetime' object is not callable

boreal ravine
#

hm

slate swan
#

how tdf

#

.created_at is a property

magic stump
#
@client.event
async def on_member_join(ctx, member):

    global hasloo


    channel = 828011225292079124

    haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

    haslo2 = 5

    hasloo = "".join(random.sample(haslo,haslo2))



    await channel.send(f"**Wyślij komendą** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")``` why bot no send to channel? nothing
slate swan
#

!d discord.Guild.get_role

unkempt canyonBOT
slate swan
#

ohhh

slate swan
slate swan
slate swan
#

i know?

#

you don't call properties

slate swan
slate swan
boreal ravine
#

it was a suggestion

slate swan
#

Mb

slate swan
boreal ravine
slate swan
final iron
#

The master version of dpy has buttons

boreal ravine
#

@slate swan whats he supposed to write then

slate swan
#

What exactly

#

Like I literally got almost everything

boreal ravine
#

nice

slate swan
#

I just need that its not able to be clicked

slate swan
#

in the code you just sent you're calling the property

#

😂

#

🤦‍♂️

slate swan
#

Lmao

slate swan
#

i think you haven't read my posts before

slate swan
#

just remove the brackets

slate swan
#

no i didn't, i posted my code and asked what I could do to solve error i was getting, kyle told me to change it to created_at() and i sent him the error, then I changed back to mine

#

oof

#

!d discord.Guild.created_at

unkempt canyonBOT
slate swan
slate swan
#

created = embed.timestamp(ctx.guild.created_at)
TypeError: '_EmptyEmbed' object is not callable

#

this is the error im getting

magic stump
#

this ```py
@client.event
async def on_member_join(ctx, member):

global hasloo

channel = discord.utils.get(client.get_all_channels(), guild__name=f'{ctx.guild.name}', name='【✅】weryfikacja-1')

haslo = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

haslo2 = 5

hasloo = "".join(random.sample(haslo,haslo2))



await channel.send(f"**Wyślij komendą** `!verify (kod)`\n**Twój kod weryfikacyjny to** \n`{hasloo}`")
slate swan
#

Does anyone know how to make buttons appear so I cannot click them???

discord-py-slash-command


boreal ravine
#

buttons appear so u cant click them? wot

slate swan
#

Yes

slate swan
slate swan
#

embed.timestamp = ctx.guild.created_at

#

If you create buttons and change some kind of property or something so you can still see it, but not click it

#

or multi-assignment: created = embed.timestamp = ctx.guild.created_at

slate swan
#

ahh

#

Its embed.timestamp isnt it

#

Uh

#

Wwll

boreal ravine
#

@slate swan I think ik ur error

#

ctx.guild.created_at returns 2021-08-25 10:07:29.575000+00:00

#

and It cant be converted into a timestamp

slate swan
#

???????

boreal ravine
#

what

slate swan
#

!d discord.Embed.timestamp

unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

slate swan
#

"what"

#

XD

boreal ravine
slate swan
#

.created_at returns a datetime object

boreal ravine
#

yes

slate swan
#

that's how you put the timestamp in an embed

boreal ravine
#

hm

slate swan
#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Voice region: europe
Roles: 91
Member status: status_online 55,151 status_offline 213,210

Members: 268,361

Helpers: 130
Moderation Team: 31
Admins: 15
Owners: 3
Contributors: 45
Leads: 13

Channels: 233

Category: 30
News: 8
Staff: 71
Stage_Voice: 2
Text: 112
Voice: 10

slate swan
#

embed.timestamp = created = ctx.guild.created_at

#

ya I did

#

but it doesn't work like this command

#

that'll set the timestamp and make the variable created

#

I can't hover over the timestamp

#

i-

coral vessel
#

So i write welcome dm message with this

bot = commands.Bot(command_prefix = '!', intents=intents)
bot working fine with dm message.

but my command prefix did't work!
if i delete intents=intents command Work again, but welcome dm message did't work.
how to resolve this ?

slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
slate swan
#

say that first ffs 🤦‍♂️

#

ahh

#

im stupid, sorry

#

wait

coral vessel
slate swan
#

embed.timestamp = created = ctx.guild.created_at.format_dt(style=relative)

#

weird

#

is this correct?

#

nope

#

that's very wrong

#

fuck, im so bad at understanding docs

#

discord.utils.format_dt is a function that takes a datetime object and a style

#

ahh

slate swan
#

discord.utils.format_dt(ctx.guild.created_at, style=R)

#

also remove embed.timestamp since that's far from what you want

slate swan
#

ah I see

#

ty

#

yw

#

wait

#

discord.utils doesn't have a method called format_dt

#

i get an error

slate swan
#

what's your dpy version

#

how do i check?

hasty iron
#

print discord.__version__

slate swan
#

did you install it from the pypi?

#

pypi?

hasty iron
#

bruh

slate swan
#

🤦‍♂️

boreal ravine
#

python package installation

slate swan
#

ah

boreal ravine
unkempt canyonBOT
slate swan
#

ty kyle

boreal ravine
#

ok

slate swan
boreal ravine
slate swan
#

why?

#

the pypi version doesn't have it

#

pypi version outdated asf

#

then all my code wont work?

#

you'll also need to do some rewriting

#

pst man I got no time for that

#

¯_(ツ)_/¯

hasty iron
#

then install from master branch

slate swan
#

so the discord version I have doesn't have format_dt huh

#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Voice region: europe
Roles: 91
Member status: status_online 54,753 status_offline 213,608

Members: 268,361

Helpers: 130
Moderation Team: 31
Admins: 15
Owners: 3
Contributors: 45
Leads: 13

Channels: 233

Category: 30
News: 8
Staff: 71
Stage_Voice: 2
Text: 112
Voice: 10

slate swan
#

how do I add the custom emojis?

hasty iron
#

uh.. just add them?

slate swan
#

no shit, but what method do I need to use?

hasty iron
#

this channel has a pin about emojis

#

lookfor it

coral vessel
slate swan
slate swan
slate swan
#

custom emoji

#

yeah, as i said, <:emoji_name:emoji_id>

#

but it wont be available for other servers?

#

if your bot can see the emoji it will work

#

why wouldn't it be available for other servers

hasty iron
slate swan
#

oh

#

so if i have 1 emoji in my server, I run the command in another server, how can it get that emoji in this server

#

dude, just pass <:emoji_name:emoji_id

boreal ravine
slate swan
#

where you replace them accordingly with your emoji's info

slate swan
#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Voice region: europe
Roles: 91
Member status: status_online 53,953 status_offline 214,408

Members: 268,361

Helpers: 130
Moderation Team: 31
Admins: 15
Owners: 3
Contributors: 45
Leads: 13

Channels: 233

Category: 30
News: 8
Staff: 71
Stage_Voice: 2
Text: 112
Voice: 10

slate swan
#

click on the green and the grey circle emoji

#

how can I add that to a string

#

if your bot can't see the emoji, then you can't add it

#

idk what you mean

#

if your bot is not in the same server where the emoji is, your bot can't use the emoji

#

yes exactly

#

that's what im saying

#

but those emojis are not in this server

#

you can do \emoji to get it formatted already

#

u don't understand

hasty iron
#

and you’re not explaining

slate swan
#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Voice region: europe
Roles: 91
Member status: status_online 53,953 status_offline 214,407

Members: 268,360

Helpers: 130
Moderation Team: 31
Admins: 15
Owners: 3
Contributors: 45
Leads: 13

Channels: 233

Category: 30
News: 8
Staff: 71
Stage_Voice: 2
Text: 112
Voice: 10

slate swan
#

those two emojis, the green and the gray one

#

is not a emoji in this server

hasty iron
#

"how do i put emoji"

slate swan
#

how does it access it

#

i fucking explained you more than 5 fucking times i'm fucking done 🚶‍♂️

hasty iron
#

it’s in another server that the bot is in?

#

use your brain

blissful crane
slate swan
hasty iron
#

they never mentioned "command"

hasty iron
#

i dont know where you got that from

reef shell
slate swan
#

my no ingliz

#

it wont work

hasty iron
#

let me just telepathically see your code real quick

slate swan
#

member_status = (
f" :online_misa: {online_presences:,} "
f" :offline_misa: {offline_presences:,}"
)

hasty iron
#

very much helpful

slate swan
#

Member status: :online_misa: 2 :offline_misa: 0

#

is the output i get

hasty iron
#

wow you totally missed the point on how to send emojis

slate swan
#

<:online_misa:emoji_id> correct?

hasty iron
reef shell
#

I'm waiting to see him send the !server command again

slate swan
lunar helm
slate swan
#

wait

#

!server

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Voice region: europe
Roles: 91
Member status: status_online 53,425 status_offline 214,938

Members: 268,363

Helpers: 130
Moderation Team: 31
Admins: 15
Owners: 3
Contributors: 45
Leads: 13

Channels: 233

Category: 30
News: 8
Staff: 71
Stage_Voice: 2
Text: 112
Voice: 10

hasty iron
#

LOL

slate swan
#

😂

#

but it says :status_online:

#

i'm dying 😂

hasty iron
#

man

#

this guy

lunar helm
#

what so funny

slate swan
#

idk they like to make fun of me

hasty iron
#

right because we explained this like 4 times

slate swan
#

ah it works

reef shell
#

🎉

slate swan
#

#bot-commands

lunar helm
#

someone help me

slate swan
#

ok

#

another issue guys

slate swan