#discord-bots

1 messages · Page 86 of 1

faint sapphire
#

what would that change

#

cause fetch doesnt yield

slate swan
#

what do you want it to do exactly

honest shoal
#

hold on lemme check the docs, there was something I remember

slate swan
#

@faint sapphire

faint sapphire
#

or to move on with code

#

maybe a while loop idk

#

oh shit the try except thing does work

#

thanks so much

slate swan
#

ig the way you're describing it if-else statement would work

#

Oh

faint sapphire
#

its so weird that try except works for something that simply doesnt give an output

slate swan
#

yeah if it's raising an error it'll work

faint sapphire
#

but maybe it does it too soon

#

uk what i mean

slate swan
faint sapphire
#

apparently it does, wasnt obvious before cause output had nothing

honest shoal
#

yes you will get NotFound error if user with that id doesn't exists

faint sapphire
#

discord is rly good

#

but theyre not profitable, rip it might disappear some day

primal token
#

Just use in?

honest shoal
faint sapphire
faint sapphire
#

they only make ab 200 million

#

nowhere close for operational costs

primal token
#

What?

#

Where did you get that number

mental hollow
#

Heya, anyone know why this is happening?
Here’s my error:

Ignoring exception in on_message_delete
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/fun.py", line 46, in on_message_delete
    del sman[message.channel.id]
KeyError: 957080091383463958

Here’s my code:

smc = {}
sman = {}
smad = {}
smaa = {}
rn = {}
stamp = {}

class Fun(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.config = default.config()
         
    @commands.Cog.listener()
    async def on_message_delete(self, message):
        if message.author.bot:
            return
        global smc
        global sman
        global smad
        global smaa
        global rn
        global stamp
        
        smc[message.channel.id] = message.content
        sman[message.channel.id] = message.author.name
        smad[message.channel.id] = message.author.discriminator
        smaa[message.channel.id] = message.author.display_avatar.url
        rn[message.channel.id] = datetime.now(timezone.utc)
        stamp[message.channel.id] = discord.utils.utcnow()
        await asyncio.sleep(3600)
        del sman[message.channel.id]
        del smc[message.channel.id]
        del smad[message.channel.id]
        del smaa[message.channel.id]
        del rn[message.channel.id]
        del stamp[message.channel.id]
       
    @commands.command()
    @commands.guild_only()
    async def snipe(self, ctx):
        channel = ctx.channel
        try:
            e = discord.Embed(color=0x2f3136)
            e.title = f"Message from #{channel}, {discord.utils.format_dt(stamp[channel.id], style='R')}:"
            e.description = f"{smc[channel.id]}"
            e.timestamp = rn[channel.id]
            e.set_footer(text=f"Message deleted: ")
            e.set_author(name=f"Message author: {sman[channel.id]}#{smad[channel.id]}",icon_url = smaa[channel.id])
            await ctx.send(embed=e)
        except KeyError:
            return await ctx.reply("I found nothing to snipe.")
faint sapphire
#

yh, they rely on constant investments

#

i might be messing up the numb, cause it was from a vid i watched a year ago

primal token
#

!e

print(None or 1)

If the first value is falsy it goes for the second value

unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

1
honest shoal
faint sapphire
#

its like netflix, theyre big but never were profitable
and might never be

brazen raft
#

!or @untold iron

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
untold iron
left idol
#

if i have a command that i want to have a "shared cooldown" how would i go abouts it? for example someone runs /poop and i want there to be 30s inbetween the next person who uses it?

unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
brazen raft
#

There is an example

feral frost
#

how to make a slash command cooldown ?

abstract kindle
#

Anyone willing to show me a general setup for a python project?

#

Like repository setup, how you access SQL database, file setup etc

#

I'm finding myself making huge messes of multiple files / downloads trying to find a clean way to setup a project

wicked atlas
abstract kindle
#

How is it deployed?

wicked atlas
#

They run their services on a Kubernetes cluster hosted on Linode

slate swan
#

oh lol i misunderstood the question

#

my bad

wicked atlas
#

I believe it gets deployed using a Github Action that deploys it to the cluster

#

probably much more complicated than you want or need actually

#

for python discord it's probably great

abstract kindle
#

I see

#

How should I deploy a basic github project

#

So far I've just been running it off of my pi

#

But I find it very hard to test/run new code when it's hosted on the pi (I primarily code on my PC)

#

I would use SSH, but it's disabled on my college network

#

Also, which SQL database should I use? Don't want to pay for anything since it's a really small project, but I want to be able to work on the project from multiple computers, so a local database wouldn't work

twin mantle
quaint epoch
#

you can have a db on there

untold iron
#

Hey there i have created a simple command to create a new channel anytime the code !newtransaction is run, when that channel is created i want the async def newtestt function to run as soon as the channel is created, however i call that function on my channel creation command, when i call await channel.send(newtestt) i end up with this message in the new channel

mental hollow
twin mantle
#

you are trying to delete something but you dont know if its actually there?

mental hollow
#

yeah

twin mantle
#

1s

#
try: # do this
    del dict["key"]
except KeyError: # if the above code errors with the error "KeyError" do this
    pass # pass keyword. litterally does nothing except end the indentation
abstract kindle
twin mantle
# untold iron

my guess would be that you are not running newtestt, to run a function you need the brackets. rn you are just passing this function in as an argument and that is what comes out then
instead do

await.channel.send(newtestt())

if you have any arguments for it pass them accordingly

twin mantle
#

ok i looked at your code for one second and you are trying to send from two different positions

#

either pass in the arguments like ctx into hte function and send it

#

or use return at the end of the function, returning the string to send into the channel

#

anyways, can anyone help me dynamically loading cogs from files?

untold iron
#

Error in terminal when running the command though discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: newtestt() missing 1 required positional argument: 'ctx'

#

I try pass ctx in the brackets

#

Prints this, not too sure why im very new to this sorry if its simple

twin mantle
#

newtestt() missing 1 required positional argument: 'ctx' this is the important part, i think you can figure it out yourself

#

how again do you call a function with arguments?

#

wait whaaskjndakjsd i thought i knew the error and just looked at your code lmao

untold iron
#

newtestt(ctx)

#

?

abstract kindle
#

I’ll explain one sec

twin mantle
#

1s

#

yea you do it yes no work for me i love it

untold iron
twin mantle
#

or send the whole code, maybe then i could see the error

untold iron
#

Sure thing

#
from discord.ext import commands
import discord
import token
import asyncio

from config import TOKEN

intents = discord.Intents.all()
client = commands.Bot(command_prefix = '!', help_command=None, intents=intents)

@client.event
async def on_ready():
    print(f'{client.user} is online')


async def newtestt(ctx):
    NewchannelName = 'HAHAHA'
    Newguild = ctx.guild

    Newmbed = discord.Embed(
    title = 'Test',
    description = "{} has been successfully Tested.".format(NewchannelName)
    )
    await ctx.channel.send(embed=Newmbed)


@client.command()
async def newtransaction(ctx):
    channelName = 'Transaction'
    guild = ctx.guild

    mbed = discord.Embed(
    title = 'Success',
    description = "{} has been successfully created.".format(channelName)
    )
    if ctx.author.guild_permissions.manage_channels:
        channel = await guild.create_text_channel(name='{}'.format(channelName))
        await ctx.send(embed=mbed)
        await channel.send(newtestt(ctx))



@client.command(name='delete')
async def delete_subcommand(ctx, channel: discord.TextChannel = None):
    if not channel:
        await ctx.send("You must provide a channel.")
        return
    await channel.delete()
    await ctx.send(f"{channel} has been removed.")




@client.command()
async def botdm(ctx): 
  await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')



client.run(TOKEN)```
twin mantle
#

for bigger codes use
```py
<your code>
```

untold iron
#

Tyvm

twin mantle
#

also the py for color codding because we all love colors

untold iron
#

Ohh

twin mantle
#

i would remove this await channel.send(newtestt(ctx)) and instead newtestt(ctx)

#

else you are trying to send stuff multiple times

#

i think that might have been the error also, trying to call .send without a message because newtestt doesnt return anything

#

or replace it by await ctx.send(embed=newtestt(ctx)), and return the embed at the end of the function newtestt

untold iron
#

Ouch

#

Oh my bad, reread let me try that

untold iron
#

Im not sure might be wrong

#

But then the part im confused on is how can i return the embed in the function? isnt it already embedded through ``` await ctx.channel.send(embed=Newmbed)

twin mantle
#

in the last line of the newtestt, instead of sending the embed, return the embed

untold iron
prime cloak
#

#Traceback (most recent call last):

2

E  File "/home/user_712497713043734539/main.py", line 54, in <module>

3

6    decoded_data=f.text.encode().decode('utf-8-sig')

4

CAttributeError: '_io.TextIOWrapper' object has no attribute 'text'

This is made with nextcord a maintained fork of discord.oh
I will send code to helper

twin mantle
#

return <name of the embed variable>

#

".encode().decode()"

untold iron
#
    NewchannelName = 'HAHAHA'
    Newguild = ctx.guild

    Newmbed = discord.Embed(
    title = 'Test',
    description = "{} has been successfully Tested.".format(NewchannelName)
    )
    return Newmbed```
twin mantle
#

ye

untold iron
#

Thank you

#
async def newtransaction(ctx):
    channelName = 'Transaction'
    guild = ctx.guild

    mbed = discord.Embed(
    title = 'Success',
    description = "{} has been successfully created.".format(channelName)
    )
    if ctx.author.guild_permissions.manage_channels:
        channel = await guild.create_text_channel(name='{}'.format(channelName))
        await ctx.send(embed=mbed)
        await ctx.send(embed=newtestt)```
twin mantle
#

there is one thing you have to understand about python

#

EVERYTHING is an object

#

why are you sending two things

#

ohh one creator and one info what its for

untold iron
#

Yeahh

#

Tried running discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'to_dict'

prime cloak
#

Can anyone help?

twin mantle
#

sure

prime cloak
#

Yay thx

#

I will do my code

twin mantle
prime cloak
#

don't steal my token🔫

twin mantle
#

REMOVE YOUR TOKEN??

prime cloak
#

Nah

twin mantle
#

do not under any circumstances send your token in here

prime cloak
#

I'm not

#

No one can see my code

#

so it should be fine

untold iron
# twin mantle line of the code where it happend? (send it)

not sure exactly where it is , here is the whole error `Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 39, in newtransaction
await ctx.send(embed=newtestt)
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\context.py", line 841, in send
return await super().send(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1520, in send
with handle_message_parameters(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 177, in handle_message_parameters
payload['embeds'] = [embed.to_dict()]
AttributeError: 'function' object has no attribute 'to_dict'

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

Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'to_dict'`

#

Assuming its the await ctx.send(embed=mbed)

twin mantle
#

line 39

untold iron
#

Yep

twin mantle
#

again

#

you arent running the function

#

you are passing the function in as an argument

#

embed=newtestt(ctx)

#

and newtestt returns the embed

untold iron
#

await ctx.send(embed=newtestt(ctx))

#

Sorry bro, im probably being mad stupid rn, ```@client.command()
async def newtransaction(ctx):
channelName = 'Transaction'
guild = ctx.guild

mbed = discord.Embed(
title = 'Success',
description = "{} has been successfully created.".format(channelName)
)

if ctx.author.guild_permissions.manage_channels:
    channel = await guild.create_text_channel(name='{}'.format(channelName))
    await ctx.send(embed=mbed)
    await ctx.send(embed=newtestt(ctx))
#

Still throws up an error when i run the command

#

`Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\wayed\Desktop\MerchantBot\bot.py", line 40, in newtransaction
await ctx.send(embed=newtestt(ctx))
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\context.py", line 841, in send
return await super().send(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1520, in send
with handle_message_parameters(
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 177, in handle_message_parameters
payload['embeds'] = [embed.to_dict()]
AttributeError: 'coroutine' object has no attribute 'to_dict'

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

Traceback (most recent call last):
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'to_dict'
C:\Users\wayed\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py:80: RuntimeWarning: coroutine 'newtestt' was never awaited
self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback`

#

Thank you for your patience

untold iron
twin mantle
#

newtestt(ctx) becomes an embed when finished running thats how you can imagine it

#

RuntimeWarning: coroutine 'newtestt' was never awaited self._context.run(self._callback, *self._args)

#

newtestt is an async defined function, how does one call those?

#

also no worries i have plenty of time

untold iron
#

Hahahah ty

#

Await is used for async no?

twin mantle
#

yes

#

althought i am unsure if async enviroment is even needed in this case im not good with async

#

await ctx.send(embed=await newtestt(ctx))

untold iron
#

Ahhhhhhhhhhhhhhh

#

Thank you very much it works, i see now its because new test is a async function

#

Ohhhhhhhhhhhh okayyy and i wasnt awaiting for the function only for embedding

prime cloak
#

Ok i fixed it!

untold iron
#

Than you very much, im glad you made me think about it i learnt something new :))))) thanks alot dude

twin mantle
#

no prob

kindred epoch
#

How do i make an async timer?

sick birch
#

await asyncio.sleep(seconds)?

untold iron
#

Hey there, im trying to add a reaction emoji that reacts to the new message printed in my new chat, however atm it reacts to the command

#

How am i able to tell it to target the new message printed in the new chat

kindred epoch
untold iron
#

Would like it to be here

sick birch
kindred epoch
sick birch
#

If the script* goes offline

kindred epoch
#

sure that

sick birch
#

Ideally your script should never go offline

kindred epoch
#

error stops the script from running?

sick birch
#

I don't think so. You should have good error handling to deal with that

kindred epoch
#

and what about if i intentionally stop the script for updating code?

sick birch
#

That should all be handled dev side and flawlessly pushed via CI/CD

#

Extensions allow you to hot-reload without stopping the script as well

kindred epoch
#

hm i see

#

how about using a loop and calling it from the db every, lets say 30 secs?

#

subtract the current time with the time saved in db? and if its in the negatives then call the funciton

sick birch
kindred epoch
#

yea

untold iron
kindred epoch
untold iron
kindred epoch
#

easier to understand when you encounter a error and just looks better lol

#

and convenient ig

primal token
primal token
kindred epoch
#

how is there "no need to use f strings or format"?

primal token
#

Are you passing any static string or other values?

kindred epoch
#

Or you could just add "Transaction" to it instead of using f strings or format

left idol
#
for n in nateamids:
  await player.remove_roles(ctx.guild.get_role(n))

is there a better way of doing this? my goal was to: if the member had a role in a list (unknown role), get rid of that one in specific but the method i have now is removing all of them (32 roles) which is taking about 1 minute

vague relic
#

hey

#
#imports
import os
import discord
import requests
import json

#intents import
from discord import Intents

intents = Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


def get_quote():

    response = requests.get('https://zenquotes.io/api/random')
    json_data = json.loads(response.text)
    quote = json_data[0]['q'] + " -" + json_data[0]['a']
    return quote


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


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

    if message.content.startswith('$inspire'):
        quote = get_quote()
        await message.channel.send(quote)
    


my_secret = os.environ['TOKEN']
client.run(my_secret)
#

a simple code

#

which justs sends an inspirational quote from google

#

when i run it

#

shows this

sick birch
vague relic
sick birch
#

That's why

#

Replit is horrible for discord bots, don't use it

vague relic
#

it was working few secs ago

#

and all of a sudden

sick birch
#

Yeah it's pretty common

vague relic
#

it started to show this

sick birch
#

Happens to most replit users, we tell them all the same thing

vague relic
sick birch
#

VSCode and Pycharm are probably the ones I see the most

vague relic
#

local?

sick birch
#

if you're feeling adventurous, go for vim or emacs

vague relic
#

hm

rare echo
vague relic
#

cloudfare blocked MY acc

#

restricting the code to run

slate swan
#

Hi!

vague relic
#

when i tried the same from the other account, tis working perfect

slate swan
#

Can I do game development with python?

pulsar solstice
pulsar solstice
slate swan
pulsar solstice
pulsar solstice
primal token
slate swan
#

Thanks, I will try pyglet and ursina,

pulsar solstice
#

And btw why are there non discord bot related questions in this channel?

#

Lol

unkempt canyonBOT
wicked atlas
pulsar solstice
primal token
dull knot
#

Guys. Cmds that allow for custom cmds and cmds that alllow you to create custom autoresponders make use of databases, right?

#

Guess everyone's asleep lol

winged dock
#

fr

dull knot
#

Pog. That gives me another reason to learn databases lol

#

Thanks!

slate swan
dull knot
slate swan
#

yeah?

dull knot
#

https://www.youtube.com/watch?v=xaWlS9HtWYw&list=PL-osiE80TeTsKOdPrKeSOp4rN3mza8VHN You think this would be a good idea to learn SQL? After I finish with this, will probably read that site you sent yesterday

In this video we will begin learning SQL Basics. To get started writing SQL, we need to first set up a server and a database. The server we will be using for these tutorials is Postgres. We'll walk through how to download, install, and setup PostgreSQL. Then we will create our first database so that we can begin writing SQL code. Let's get start...

▶ Play video
dull knot
dull knot
slate swan
dull knot
#

Will go through this thoroughly lol. Will watch this then read that resource you sent yesterday. Alright. Thanks for the help

pseudo finch
#

I got more error in replit for discord bot Help me

left idol
#

is there a limit to autocomplete?

vale wing
vale wing
#

Why'd you even use it? Youtube tutorial or smth

slate swan
slate swan
left idol
#

Forgot to say I resolved my issue, thank you anyway though!

slate swan
#

import psutil smh

naive briar
#

Install it

slate swan
#

now since they are dynamic, you control which 25 of them to send on a particular response

slate swan
dull knot
#

Fuc. I'm stumped. Need help:

    @commands.command(name="nekoify")
    async def Neko_ify(self, ctx, *, content):
        Normal_Letters = ["L", "R"]
        for Letters in content:
            Nekoified_Txt = content.replace(f"{Letters}", "W")
        await ctx.send(content=Nekoified_Txt)

Think of this as the owoify cmd.
When I use the cmd, it just sends the string with an additional letter "W" at the very last string letter. I assume that's because of the for loop ending at the last string?
What can I do for this? Brain's becoming dumber by every second lol

slate swan
#

whats Letters? is that a list?

dull knot
#

Oh, wait. I forgot. It's supposed to be Normal_Letters

#

It still sends the same result regardless though

slate swan
#

yes, also beware that you can't check if list in str

dull knot
#

Yeah, I tried kek

slate swan
#

you need to check each element of list one by one

dull knot
#

How can I do that?

slate swan
#
if all(element in content for element in <list>)
``` should do
dull knot
slate swan
#

this will check if all elements of the list are in content

dull knot
slate swan
dull knot
slate swan
#

!d any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
slate swan
#

this may help

dull knot
dull knot
slate swan
#
import discord
from discord.ext import commands

client = discord.Client()
app = commands.Bot(command_prefix='-')
@app.event
async def on_ready():
  print(f'{app.user.name}, Logged in.')
  pass
@client.event
async def on_message(message):
  await app.process_commands(message)
  if message.content == 'hey':
    print(f'{message.author.username} : called the function')
app.run('MTA..token..p7BTo')
#

The command doesn't working

#

I got no idea, anyone please help

#

No errors

#

I tried app(client).command tough-

naive briar
slate swan
#

tutorial1.intersection(tutorial2)

slate swan
#

shall i delete one of them?

naive briar
slate swan
#

Okay, i'll try that, thanks you.

#
import discord
from discord.ext import commands


app = commands.Bot(command_prefix='-')
@app.event
async def on_ready():
  print(f'{app.user.name}, Logged in.')
  pass
@app.event
async def on_message(message):
  await app.process_commands(message)
  if message.content == 'hey':
    print(f'{message.author.username} : called the function')
app.run('MTAxOD..thesame...fnp7BTo')

STILL NOT WORKING-

naive briar
slate swan
#

message_content??? what is that tough-

naive briar
#

Also, is this dpy 2?

slate swan
#

i found lots of hell tutorial on youtube

#

so I just following it

vale wing
#

The 90% of those youtube "tutorials" are hell

#

Read the guides and docs instead

ebon mauve
#

might help

slate swan
#
import discord
from discord.ext import commands


app = commands.Bot(command_prefix='+')
@app.event
async def on_ready():
  print(f'{app.user.name}, Logged in.')
@app.command()
async def solo(ctx):
  await ctx.send("Hi")
app.run('MTA...thelatest.....mII86Fofnp7BTo')
#

yup, but, still not working

vale wing
#

What for do you need pass

#

The function is not empty

vale wing
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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

slate swan
#

AYy

vale wing
#

The code you found is outdated

#

Also yeah leave some spaces between functions (the right amount of spaces is 1 or 2 idr), your code will look better

slate swan
#

Thanks YOU

#

noone can randomly guess the solution without looking at ur code

ebon mauve
#

@slate swan

slate swan
#

the error comes from "ticket category" command's checks

ebon mauve
#

go to your shell

#

listen

#

go to your shell and just type kill 1

#

kill 1

ebon mauve
#

what are you using to code your bot?

#

I prefer you try using visual code for now

#

write your code

#

go to shell or terminal, then typ the following

kill 1

#

and press enter

#

@slate swan r u making a bot for discord??

#

at what stage r u right now?

#

of making the bot

#

thats great

#

what are your bots current running functions? or u may say, commands

#

Just asking

#

I am also making a bot and facing some issues

#

thats why

#

damn thats great...

do you think u can help me out here with my bot?? 🙂 I'm also trying to make the same with addition to some embed msgs

dull knot
#

Bruh.

Well, I'm not a pro at python but there's the error smh

#

Isn't that only for replit? For when your bot gets rate limited?

vale wadi
#

Hi

dull knot
#

Hi

#

Then I think Kill 1 won't fix that. Fix the errors in the code

ebon mauve
#

it fixed mine...same issue

dull knot
#

Or I guess try this? Everything is worth a shot to learn something new

#

If it doesn't work, then yes. You probably need to fix some code errors. Check the errors in the terminal and figure out why it's happening.

pulsar solstice
#

how to make that little icon and title in embed

#

Like <icon> Dyno

#

in the image

naive briar
#

You mean embed author?

pulsar solstice
#

but tell me how to do that

dull knot
#

embed.set_author.

pulsar solstice
naive briar
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
dull knot
ebon mauve
#

Can anyone here help me out with my bot??

My bot seems running, bt he's not taking a command here, he's taking a few commands except the embed command. Anyone here please help me out 🙂 i can show you the code

eternal fox
#

Show the code

unkempt canyonBOT
ebon mauve
#

It seems i cant paste a file here

#

@eternal fox should I dm you the code?

slate swan
ebon mauve
#

Ok

#

Its a whole .py file 🙂

dull knot
#

Copy and paste all the File in the code there

faint sapphire
#

hey, i dont want to use primary keys, but when theres a duplicate of something, is it possible to know + ignore the error and do nothing```py
sql = '''INSERT INTO mms(Server_ID, Server_Name, Server_Nickname, MM_ID, MM_Name, Invite_Code, Status) VALUES(?,?,?,?,?,?,?)
ON CONFLICT(Server_Nickname) IGNORE

onyx ravine
#

how to use jsk in dpy 2

slate swan
#

uh idk where to ask the question, but my debugger isn’t running correctly

naive briar
#

Is there anymore traceback above that

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

ebon mauve
#

here's my code, can anyone help me here??? it seems my bot is running but my bot ain't taking any command for embed options

slate swan
#

and just do await ctx.send(embed=embed) @ebon mauve

faint sapphire
#

hey, how do i know if something isnt in a database
say i input a name which doesnt exist```py
try:
await cur.execute('''SELECT * FROM itemsInfo where name = ? ''', (items))
result = await cur.fetchone()
except:
result="None"

naive briar
faint sapphire
#

yh it prints none if i add print
i was confused cause returning None didnt work

#

yh i was tryna change the value of result if it was none, and that doesnt work

naive briar
faint sapphire
#

thanks

ebon mauve
#

happens*

#

still cant use the command

naive briar
#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
naive briar
#

I'd suggest you get the unexpired invites from the server and use them before creating more

naive briar
#

You can only have one

ebon mauve
#

ok

#

I changed the whole code again can u see that now pls?

#

here

naive briar
#

You must first get a channel from the guild and then create an invite with it

channel = guild.text_channels[0]
invite = await channel.create_invite(...)
naive briar
#

And you have to be aware that every time you call that command, it will always create a new invite in the guild that it is in

#

👍

naive briar
naive briar
crimson compass
#

im new and trying to make a bot and this pops up when i run the program:

TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

slate swan
#

and don't use Client really

crimson compass
#

what should i use

slate swan
#

you can't make prefix commands using that

slate swan
crimson compass
#

ok thanks

slate swan
crimson compass
#
    async def on_message(message):
TypeError: __init__() missing 1 required keyword-only argument: 'intents'```
ebon mauve
#

Big shoutout to @eternal fox he helped me out in my code's ❤️ love u bro

crimson compass
shrewd apex
slate swan
#

you already have it huh

#

don't install it smh

crimson compass
#

ok

crimson compass
#

there are many errors

#

about the bot.run

rugged sigil
#

I am new to python and i am trying to make an bot that moves user but it shows error from line 4 idk how to fix it!

import discord 
from discord.ext import commands 

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

TOKEN = "Secert"

@bot.command() 
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
 await member.move_to(channel) 
 print("move started")

@bot.event 
async def on_ready():
 print("Ready")
bot.run(TOKEN)

Error:

TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'```
#

Please anyone could help?

slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

slate swan
#

why does everybody have the same issue lmao

rugged sigil
#

begginer 😐

crimson compass
# slate swan nice what's it
[2022-09-17 12:19:24] [INFO    ] discord.client: logging in using static token
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\PYBOT\main.py", line 10, in <module>
    bot.run("token")
  File "C:\Users\User\PycharmProjects\PYBOT\venv\lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
#

there are more errors i just cant send it all

slate swan
#

!paste paste them here

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.

#

Hey @crimson compass!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crimson compass
#

its too big

slate swan
#

use the paste bin smh

unkempt canyonBOT
#

Hey @crimson compass!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crimson compass
#

press on it and you should be able to see it

short silo
#
channel_name=blah blah blah
        Channels = guild.text_channels
        print(Channels)
        print(channel_name)
        if channel_name in Channels:
            return
        
```  i am getting Channels  as an empty list
crimson compass
shrewd apex
#

enable the intents on ur bot dev page

short silo
#

oh alr thnx

crimson compass
short silo
shrewd apex
#

who broski?

short silo
#

same problem as me

slate swan
#

You need to enable the intents feature from the discord developers tab.

short silo
#

enable intent

slate swan
#

I just enable these 3.

crimson compass
#

cant find them brat

slate swan
#

It's in the Bot section.

crimson compass
#

if it works i love you guys

slate swan
#

It will work.

crimson compass
#

I LOVE YOU GUYS❤️

rugged sigil
# slate swan !intents

i did this and it gives me big fat error
code:

import discord 
from discord import Intents
from discord.ext import commands

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

bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"

@bot.command() 
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
 await member.move_to(channel) 
 print("move started")

@bot.event 
async def on_ready():
 print("Ready")
bot.run(TOKEN)
slate swan
slate swan
rugged sigil
#

what i should do?

slate swan
rugged sigil
#

okay

slate swan
#

and hit the Bot tab, and from there enable all the settings under Privileged Gateway Intents

short silo
slate swan
#

That is it, re-run your bot.

rugged sigil
#

it doesn't do the job

short silo
#

Then code wrong O-O

slate swan
#

That is to do with your program.

short silo
#
channel_name=blah blah blah
        Channels = guild.text_channels
        print(Channels)
        print(channel_name)
        if channel_name in Channels:
            return

i am getting Channels as an empty list

slate swan
#

First, check if it's reading any channels, do

for _ in Channels:
    print(_)
#

This should output all the channels.

short silo
slate swan
#

Yes.

short silo
rugged sigil
#

could someone help me?

import discord 
from discord import Intents
from discord.ext import commands

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

bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"

@bot.command() 
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
 await member.move_to(channel) 
 print("move started")

@bot.event 
async def on_ready():
 print("Ready")
bot.run(TOKEN)

i program lua and i am new to discord.py i just wanted bot that just move members like this $move @rugged sigil channel voice....

please!!!!!!!!

slate swan
#

Well, i'm not the best at discord.py, ask someone who is experienced i don't want to give help i'm not sure about.

slate swan
short silo
slate swan
#

I see

#

does the server have any text channels 💀

slate swan
short silo
slate swan
short silo
slate swan
#

ic

short silo
#
@bot.event
async def on_raw_reaction_add(payload):
    message = payload.message_id
    emoji=payload.emoji.name
    if message in Cache.Messages_to_Track and emoji=="📩":
        user_discord_name = str(await bot.fetch_user(payload.user_id))
        user=await bot.fetch_user(payload.user_id)
        guild=await bot.fetch_guild(payload.guild_id)
        channel_name=user_discord_name.replace('#','')
        Channels = guild.text_channels
        if channel_name in Channels:
            return
        overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        user: discord.PermissionOverwrite(read_messages=True)
    }
        channel = await guild.create_text_channel(channel_name,overwrites=overwrites)
        embed = Embed(title="Form Filling",color=discord.Colour.purple(),description=f"bleh")
        await channel.send(embed=embed)
#

entire code block

short silo
slate swan
#

f

#

what I can make out is intents issue or no text channels

short silo
#
Intents = discord.Intents.all()
GUILD=[bleh]
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$"), intents=Intents)
#

o_O @slate swan

crimson compass
#

i want to make my bot to make a message embed without having to use a command

crimson compass
rugged sigil
#

could someone help me?

import discord 
from discord import Intents
from discord.ext import commands

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

bot = commands.Bot(command_prefix="$", intents=intents)
TOKEN = "secert"

@bot.command() 
async def move(ctx, member : discord.Member, channel : discord.VoiceChannel):
 await member.move_to(channel) 
 print("move started")

@bot.event 
async def on_ready():
 print("Ready")
bot.run(TOKEN)

i program lua and i am new to discord.py i just wanted bot that just move members like this $move @rugged sigil channel voice....
**
please!!!!!!!!**

short silo
crimson compass
#
@bot.command()
async def commands(ctx: commands.Context, text: str) -> None:
    embed = discord.Embed(title="**Commands**", description=".embed \n.commands", colour=0x053305).set_thumbnail(url='https://cdn.discordapp.com/attachments/1020646324472926221/1020662000025608222/unknown.png')
    await ctx.send(embed=embed)```
it works when i use it with .commands (and add text) but it doesn't work with just .commands
#

anyone?

pulsar solstice
#

how to get the number of users of a discord bot

#

okay

crimson compass
#

what should i put

glad cradle
#

it's len(bot.users) since it returns a list

rugged sigil
#

something like $ because i am wroking in project

#

and i need that bot rn

glad cradle
glad cradle
crimson compass
#

thank you

glad cradle
#

if no argument is provided when invoking the command then text will assume None as value

open narwhal
#

is pebblehost any good for hosting bots? what would y'all recommend?

twin mantle
open narwhal
#

I used to host my discord.js bot on repl.it before, used to go down occasionally, not a fan. It's hosted on heroku now but they are shutting down their free tier. Currently moving my .js implementation to .py.
I don't mind paying a bit to keep it running though. If y'all got any other suggestion/recommendation lemme know, thanks!

glad cradle
#

there's oracle's free tier

open narwhal
#

oracle hmmm

twin mantle
#

i myself use a rasberry pi 3b+ with ssh and ftp server installed to access files,
i develope a bot with my desktop pc with a token connected to a test bot and my rasberry pi always runs the actual bot with the code that was already uploaded. i heard you can do reloading on an event from file changed so automatic reloading can also be done

#

but it is around 40-50 bucks not sure rn

open narwhal
#

I see, I don't have a raspberry pi though but that sounds like a fun project

proven ore
#

man im bored

#

im bored man

#

bored im man

winged coral
#

ha

twin mantle
#

hi bored im mom

proven ore
hushed galleon
open narwhal
#

ooh thats sick thank you very much

warm lava
#

can someone pls help

#
AttributeError: 'Button' object has no attribute 'response'
hushed galleon
#

can you show your code? id guess that you have (self, button, interaction) as your parameters, which need to be flipped around to (self, interaction, button) in dpy 2.0

warm lava
#
class Buttons(discord.ui.View):
    def __init__(self, *, timeout=180):
        super().__init__(timeout=timeout)
    @discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
    async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
        await interaction.response.edit_message(content=f"This is an edited button response!")

@client.command()
async def button(ctx):
    await ctx.send("This message has buttons!",view=Buttons())
hushed galleon
#

yup

#
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):``` you need to switch `button` and `interaction` around
warm lava
#

why does it have to be in that order in the first place anyways?

hushed galleon
#

originally during development it was (self, button, interaction), but then they changed it to (self, interaction, button) for the final release for "consistency" i think they said

primal token
#

Thats the order the library internally passes arguments upon an pressing a button

warm lava
#

ahh, i see

#

thanks ulit

#

idk the english equivalent of "ulit"

hushed galleon
warm lava
#

hmm

untold iron
#

Anyone know how i can setup source control with my project, nothing large scale crazy just a simple commit and ability to revert. All the tutorials on youtube seem crazy complex?

slate swan
untold iron
#

My bad, which channel should i ask in?

slate swan
lusty coral
#

Friends, I'm trying to add my bot to the server, I can't add it, can anyone help?

chrome bison
#

you get a perpetually free 1.5GB 2 core VM here

dusk girder
lusty coral
lusty coral
dusk girder
#

try going through the discord developer website

#

go to your bot application
on the left, oauth > url generator

#

select bot, then choose permissions you want

#

that'll spit out a link that you can use to add your bot to servers

crimson compass
#
    async def ip(ctx: commands.Context, text: str = None) -> None:
AttributeError: 'Command' object has no attribute 'Context'```
dusk girder
#

did you name a variable the same as the module?

lusty coral
#

@dusk girderI can't use google transate, sorry for my english, I can't get any interaction when I click on the following sections, what should I do?

dusk girder
#

you able to show me what you see?

dusk girder
#

assuming commands is a module, that is

crimson compass
#

yeah

dusk girder
#

yeah try naming the variable something else, or doing import commands as <alias>

robust fulcrum
#

Guys how can I send dm to user thought discord v8 api?

lusty coral
honest shoal
lusty coral
robust fulcrum
honest shoal
#

yes

robust fulcrum
#

Ye

#

I will use it in my website

honest shoal
lusty coral
dusk girder
#

not application.commands, bot

#

then choose permissions you want the bot to have on your server

honest shoal
# robust fulcrum I will use it in my website

I believe most of the people here do not use raw requests, you can ask at discord developers server if you get any doubt.
here's how you can create DMs - https://discord.com/developers/docs/resources/user#create-dm
by the way, v8 is deprecated

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

robust fulcrum
dusk girder
#

(bot is here btw)

#

you get it to work?

#

also I never had to select applications.commands and it worked fine

honest shoal
#

and then you can send msg to that channel

honest shoal
dusk girder
#

application commands like /command or am I misunderstanding?

honest shoal
#

slash commands and context menu commands

#

both of them together are called as application commands

dusk girder
#

context menu??

never heard of that one before, I'll have to try them lol

#

also by just selecting "bot" I can still use slash commands so idk lmao

crimson compass
#

how do i make my bot delete the command ive typed
ex. i type hello and it replies with hi and it deletes the hello

dusk girder
#

presumably await msg.delete()

dusk girder
#

yeah I'm definitely trying these when I get home that's cool

crimson compass
# dusk girder presumably `await msg.delete()`

do i put it like this?

@bot.command()
async def embed(ctx: commands.Context, *, text: str) -> None:
    embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(url=ctx.author.display_avatar.url)
    await msg.delete()
    await ctx.send(embed=embed)
honest shoal
#

no

crimson compass
#

how

dusk girder
#

oh so that's a context not a message I seee

crimson compass
#

yeah

dusk girder
#

idk what attributes the context class contains

honest shoal
#

ctx.message

dusk girder
#

ok that's what you want then

#

ctx.message.delete, not msg.delete

thorn seal
#

how do i check a user for permissions using interation

crimson compass
#

and do i put it where i put await msg.delete()

honest shoal
dusk girder
#

after the ctx.send*

crimson compass
#

it doesnt delete it

dusk girder
#

idk then lmao

honest shoal
crimson compass
#
@bot.command()
async def embed(ctx: commands.Context, *, text: str) -> None:
    embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(url=ctx.author.display_avatar.url)
    await ctx.send(embed=embed)
    ctx.message.delete```
dusk girder
#

await ctx.message.delete()

naive briar
#

You need to await it

crimson compass
#

thanks

dusk girder
naive briar
#

🥴

glad lagoon
#

How could i get the last 2 messages of a channel?

vocal snow
unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
vocal snow
#

the limit and oldest_first kwargs should help

glad lagoon
#

I had it kind of setup that way before but with less args

tidal hawk
#

Remove the *

glad lagoon
#

Did that

#

renamed message to number because well i already use message. But number.content just returns whitespace

tidal hawk
#

send full code snippet

glad lagoon
#

Or do you mean the entire method?

tidal hawk
#

Entire command yeah

glad lagoon
#

Command?

#

I didn't write most of this as this is a custom fork of a bot

#

Also this was before /commands

tidal hawk
glad lagoon
#

this one?

tidal hawk
#

mhm

#

And also you do not need these None kwargs, just leave the limit one there

glad lagoon
#

so this should work?

tidal hawk
#

Yeah it should

glad lagoon
#

Nope just whitespace again

tidal hawk
#

Maybe the oldest messages had some weird formats

#

set limit to 20 and maybe smth changes

glad lagoon
#

Shouldn't since i just sent a normal message

glad lagoon
tidal hawk
#

Does that part of the code get executed for sure? add print('test') above print(number.content)

glad lagoon
#

Considering the fact it's printing 20 lines of whitespace...

tidal hawk
#

Oh, welp

glad lagoon
tidal hawk
#

what does number.author return?

glad lagoon
#

It works

#

Printing just the message it throws out all the data and stuff but i see no content

tidal hawk
#

Send a picture of these messages xd

glad lagoon
#

Might be a bit hard cause they go off screen

tidal hawk
#

From Discord text channel

glad lagoon
#

<Message id=984508464548167701 channel=<TextChannel id=984502146185691157 name='counting-test' position=11 nsfw=False news=False category_id=474783551326519319> type=<MessageType.default: 0> author=<Member id=236195385415172106 name='DangerMage' discriminator='1696' bot=False nick=None guild=<Guild id=474783551326519317 name='MY MUSIC' shard_id=0 chunked=True member_count=7>> flags=<MessageFlags value=0>>

glad lagoon
naive briar
glad lagoon
naive briar
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

tidal hawk
#

goddamn intents, I usually enable them without thinking xD

glad lagoon
#

How do i enable it?

pulsar solstice
naive briar
glad lagoon
#

Do i need to do that inside my class or outside my class?

naive briar
slate swan
#

discord.py - how to make a bot work only when you have a role?

glad lagoon
tidal hawk
glad lagoon
#

Do i need to reinvite it now?

tidal hawk
naive briar
#

Nah

tidal hawk
#

Thought Discord bots had cool features, until saw Telegram ones xd

glad lagoon
naive briar
glad lagoon
#

Now to compare them and make a counting game >:D

tidal hawk
#

or you can just do:

if role_id in [role.id for role in ctx.author.roles]:
...

glad lagoon
#

should be all i need?

#

(full bit of the counting part)

tidal hawk
#

convert content to integer

glad lagoon
#

Oh right

#

I should check if it's a digit first

tidal hawk
#

yess

#

string.isdigit()

glad lagoon
#

yup

#

so more like this?

naive briar
tidal hawk
#
  • translation - delete -> delete()
glad lagoon
#

Oh

tidal hawk
#

Bruh

naive briar
#

Put the () after them

#

Yeah yeah 🫠

glad lagoon
#

ah that's what sink was translating

#

So this should be good then

vale wing
#

I bruhed

tidal hawk
#

Just give it a go xd

glad lagoon
#

It's uh. deleting the number before the 2...

#

And doesn't delete the message if it isn't a digit

vale wing
#

Are you trying to make counting game

glad lagoon
#

Yes

vale wing
#

You just gotta fetch the last number on bot startup and save it, then compare it to the new messages and update it

#

History method is easily breakable

glad lagoon
#

I have no idea where in this fork i would add that

#

found it

#

probably want to do it here

glad lagoon
vale wing
#

Depends in what context

glad lagoon
#

well i found the startup file or at least a spot close enough where i think it would be safe to retrieve the last number but it's in a different class in a different file

tidal hawk
glad lagoon
#

It's doing stuff wrongly

#

I made it delete words now but it still deletes numbers

tidal hawk
#
if message.channel.id == 1020721733407359089:
            messages = await message.channel.history(limit=2).flatten()
            if not message.content.isdigit() or not int(messages[1].content) + 1 == int(message.content):
                await message.delete()

``` Just created that, it should work
glad lagoon
#

And can't bots not get history if the message is too old?

tidal hawk
#

Why do you want to fetch the oldest message? :D

glad lagoon
#

Not the oldest one but the counting game channel we have goes inactive every now and then

tidal hawk
#

But yeah his method is better ig

glad lagoon
#

I mean, slow mode is a thing

tidal hawk
#

Mhm, but if 15-20 ppl enter a number at the exact same time, then it might become a problem

glad lagoon
#

hmm

#

Isn't his method breakable at that point as well?

#

well. i guess just check if the message is a digit then compare to the stored number would work if it does it for every message

tidal hawk
#

mhm

glad lagoon
glad lagoon
#

just doesn't work in general

slate swan
#

how to whitelist people to use my bot

unkempt canyonBOT
#

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

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

glad lagoon
#

Good bot

glad lagoon
rare jewel
#

so how would i do it with docker?

sick birch
unkempt canyonBOT
sick birch
#

check out our bots repo to see how we do it

torn sail
#

I have a server that has been around for a week and a server that has been around for a year. Both are community servers. However only the one that has been here for a year can make a forum channel. Is there some sort of server age limit to make forum channels?

#

I tried to make the forum with my bot but I got this error

#
Traceback (most recent call last):
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\features\python.py", line 156, in jsk_python
    async for send, result in AsyncSender(executor):  # type: ignore
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\functools.py", line 125, in _internal
    value = await base.asend(self.send_value)
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\repl\compilation.py", line 154, in traverse
    async for send, result in AsyncSender(func_g(*self.args)):  # type: ignore
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\jishaku\functools.py", line 125, in _internal
    value = await base.asend(self.send_value)
  File "<repl>", line 1, in _repl_coroutine
    await _ctx.guild.create_forum('Homework Help')
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\discord\guild.py", line 1634, in create_forum
    data = await self._create_channel(
  File "C:\Users\chawk_jbu1gcm\PycharmProjects\booksehfl2\venv\lib\site-packages\discord\http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50024): Cannot execute action on this channel type

glad cradle
torn sail
#

I’m basically wondering what I need to be able to make forum channels

slate swan
#

you need to enable and actually have possibility to create that channels

glad cradle
wicked atlas
torn sail
#

Thank you for the responses!

slate swan
#

10 bots with one user...

torn sail
#

I assume that older servers are getting them first

sick birch
#

Got code?

glad cradle
#

oops wrong message

gusty shard
#

they are looking so close

#

how can i put them further

#
embed=discord.Embed(title=f"{message.author.name}'s stats", description=f"Started journey on {zaman}", color=0xffa3d9)
embed.add_field(name=f"Made {data[id]['stats']['max money']} in total", value=f"Lost {data[id]['stats']['losted money']} in total", inline=True)
embed.add_field(name=f"Boguht {data[id]['stats']['cnsbought']} coins", value=f"Sold {data[id]['stats']['cnssold']} Coins", inline=True)
embed.add_field(name=f"Gambled {data[id]['stats']['gamble']} times", value=f"Won {data[id]['stats']['sccsgamble']} of them", inline=True)
embed.add_field(name=f"Worked {data[id]['stats']['work']} times", value=f"Answered {data[id]['stats']['sccswork']} of them correct", inline=True)
embed.add_field(name=f"Wrote a sentence has 'hbc' on it {data[id]['stats']['hbc']} times", value=f"And make ${data[id]['stats']['hbcgain']} from that", inline=True)
embed.set_footer(text="If you think something is wrong, contact with us!")     
await message.channel.send(embed=embed)```
#

thats the embed

slate swan
#

you don't control them, discord does ;-;

gusty shard
#

so its impossible to make it look good

#

embed generator i used shows it like that

wicked atlas
#

Yeah, can't change how discord displays stuff

#

You could just make them not inline

finite jay
#

!voiceverify

wicked atlas
#

Or, you could display your text in a different way, like just putting it in the description with markdown

**Hello:** World
**Statistic:** $1000000000
**Meaning of Life:**: 42
glad cradle
gusty shard
wicked atlas
gusty shard
#

is it chr(173)?

gusty shard
#

they are still too close 😩

wicked atlas
#

Looks fine to me. That’s about as spaced you’re going to get fields.

glad cradle
pliant gulch
#

Also consider spicing things up with ASNI Code-blocks (if you don't care about mobile rendering)

twin mantle
#

uhm would anyone have some code for me that reloads cogs because im lazy?

#

asking for a friend

rare echo
slate swan
#

How do i retrieve the message authors username in Hikari lightbulb?

feral frost
#

how do i make a commands.cooldown for slash bot ?

faint sapphire
twin mantle
#

im jokin

feral frost
faint sapphire
#

idk im not an expert

feral frost
#

k

faint sapphire
#

those two ideas are the best i can make up

#

yo
my question is quite basic :/
but im in a hurry to make all the commands functioning again
for a specific channel, i want the bot to read all the messages
i used to use message.content, i now moved to bot commands and dont know if i use message.context or something like @bot.listen

vale wing
unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
vale wing
#

Check its attributes

faint sapphire
#

thanks

feral frost
vale wing
#

Oh heck dpy even uses different submodule for app commands decos 💀

faint sapphire
#

i wonder if it applies for non slash commands too

twin mantle
#

i just deleted my reddit api access and dont have access to reddit rn

#

aahahahha

faint sapphire
#

whats that pfp

feral frost
feral frost
faint sapphire
#

awesome thanks

feral frost
#

np

faint sapphire
#

awkward attempt at getting a full message's content 😵‍💫 sorry im rushing things today```py
@bot.command(case_insensitive=True)
async def filterMessage(ctx):
if ctx.channel.id in hightierschannels:
fullMessage = ctx.message.content

unkempt sinew
#

hi

feral frost
#

how do i make smth like this @commands.is_owner() in slash commands ?

slate swan
#

what library

feral frost
#

me ?

#

i use app_commands

#

idk what it is

#

but it works if that is what you mean

faint sapphire
#

idk i just use lists containing admin ids
it can also be stored in a database
but then i rely on adding admins through commands rather than roles

#

i prefer that anyway

#

not a good idea if u making a public bot tho

feral frost
#

ye

twin mantle
#

i have not implemented any security features yet

#

litterally everyone could execute litterally every command

feral frost
#

not good

twin mantle
#

ahh nobody knows the commands its only like 5 commands

#

im still working on structure, speaking of which can anyone tell me the event name for when the bot joins a new server?

#

nvm i put adding new folders for server data in my read data function

faint sapphire
#

yh before adding lists of admins i had some commands with weird names so no one discovers them lol

#

yo i cant figure out how to see the full message content without having a command name :/```py
@bot.command(case_insensitive=True)
async def filterMessage(ctx):
if ctx.channel.id in hightierschannels:
fullMessage = ctx.message.content

twin mantle
#

how do you manage files? i just wonder if there is a better way then how i am doing it

#

"".split?

faint sapphire
#

files?

twin mantle
#

to store data about users or servers

faint sapphire
#

use a database like aiosqlite
ull have to, for each ppl to save their command prefix or whatever

twin mantle
#

thats what i mean yes

#

i have never heard that name

faint sapphire
#

its an async sqlite

twin mantle
#

if you know there is going to be a space in the input command you can use "".split(" "), and then use only the second object of the tuple

#

or use *args

#
    async def echo(self, ctx, *args):
        string = ""
        for part in args:
            string += part
            string += " "
        await ctx.send(string)
#

this is my echo function

faint sapphire
#

its same as sqlite3

#

just asynchronous

twin mantle
#

ahha i never worked with sql lmao

faint sapphire
#

so it can do more things at the same time

twin mantle
#

rn i have alot of text files each with their own value stored inside of them, and a decorator to get a dict out of it, and afterwards it writes changed information back to the files

#

also i just started having this really annoying typo, i write os.listdir as os.listidr

#

happend like 5 times, even when i wrote the first os.listird ASLDMLAKSDMÖLASMDLKASMD I CANT

faint sapphire
#

sounds complicated

twin mantle
#

ehh its not that hard 1s let me get my script

#




def server_data(func):
    """
    Decorator to get/write guild data when executing a command
    """
    def inner(self, ctx):
        
        # If guild has no directory yet, create one
        if not os.path.isdir(f"./data/guilds/{ctx.message.guild.id}")
            os.mkdir(f"./data/guilds/{ctx.message.guild.id}")
        
        # Reads the preset for new guilds and so on
        presetDict = {}
        for entry in os.listdir(f"./data/guilds/preset"):
            with open(f"./data/guilds/preset/{entry}", "r") as f:
                presetDict[entry] = f.read()
        
        # Reads the data from the guild the message was send from
        guildDict = {}
        for entry in os.listdir(f"./data/guilds/{ctx.message.guild.id}"):
            with open(f"./data/guilds/{ctx.message.guild.id}/{entry}", "r") as f:
                guildDict[entry] = f.read()
        
        # Checks if guild data is in sync with preset, if not, sync
        for presetKey in presetDict:
            try:
                guildDict[presetKey]
            except KeyError:
                guildDict[presetKey] = presetDict[presetKey]
                
        newGuildDict = func(ctx, guildDict)
        
        # Finds the difference between the old (guildDict) and new (newGuildDict) guildDict
        for guildKey in guildDict:
            if newGuildDict[guildKey] != guildDict[guildKey]:
                # Changes the values in the files if there is a difference
                with open(f"./data/guilds/{ctx.message.guild.id}/{guildKey}", "w") as f:
                    f.write(newGuildDict[guildKey])
    return inner
#

anything using this decorator returns the edited (or also unedited) data

#

ima change it tho to get a tuple so i might be able to have multiple returns not sure if i might need that

faint sapphire
twin mantle
#

but then i have to learn new stuff asnasdkn

#

that is not how links work

#

dw ill use google

#

it looks good but i dont see why i shouldnt use my current script

slate swan
twin mantle
#

damn i didnt even know pycord existed

twin mantle
untold iron
#

Hey there, im learning how to code a discord bot, however the problem i have is i never know what features there are i can use. e.g. what other reaction events can i do aside from on_reaction_add e.g. is there on_reaction_remove ect

#

Is there any list or so where i can search up these and find more

twin mantle
untold iron
#

Ty will check it out

glad cradle
unkempt canyonBOT
#

discord.on_reaction_remove(reaction, user)```
Called when a message has a reaction removed from it. Similar to on\_message\_edit, if the message is not found in the internal message cache, then this event will not be called.

Note

To get the message being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").

This requires both [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.

Note

Consider using [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") if you need this and do not want to enable the members intent.
slate swan
#

which discord.py version is the best to use for bot coding

unkempt canyonBOT
vocal snow
#

That one

slate swan
#

ok ty

limber bison
#

why

crimson compass
#

how do i make my command not run if the user doesnt have a specific role/specific permission??

twin mantle
# limber bison

you cant use self outside off class functions where you gave it in as an argument

#

remove the three lines after the __init__ function

vocal snow
unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
vocal snow
#

And has_permissions for permissions iirc

crimson compass
#

thank you

twin mantle
#

if i mention someone inside of a message which gets reacted to, how can i get the id of who was mentioned?

unkempt canyonBOT
#

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

Warning

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

vocal snow
#

so in on_reaction_add you should be able to use reaction.message.mentions

twin mantle
#

1s

limber bison
twin mantle
limber bison
#

self no define

vocal snow
#

Yeah because it isn't lol

#

How is self.leng defined there

limber bison
#

explain

vocal snow
#

Explain what

#

If you need a guide on classes, check Corey Schafer's series on OOP on youtube

twin mantle
#
class foo:
    def __init__(self):
        self.length = 1 # can use self here because it is an argument
    # cant use self here because its not an argument BUT we are in the self scope so you can set a self variable like this
    length = 1
#

im not even sure if scope is the right word

crimson compass
twin mantle
#

are you using discord.Client or discord.ext.commands.Bot?

crimson compass
#

the 2nd

twin mantle
#

you are running a for loop in the class defining bruh

#

before __init__ runs

twin mantle
#

there is a commands.check, if you are using cogs, or a bot.check decorator which takes in a function to run and test various things

slate swan
#

!embed

#

!guild

unkempt canyonBOT
#
Server Information

Created: <t:1483877013:R>
Roles: 158
Member status: status_online 43,615 status_offline 311,924

Members: 355,539

Helpers: 145
Moderation Team: 38
Admins: 14
Owners: 3
Contributors: 42
Leads: 10

Channels: 331

Category: 36
News: 10
Staff: 65
Stage_Voice: 2
Text: 206
Voice: 12

slate swan
#

!embed

hazy oxide
crimson compass
#
@bot.command()
@commands.has_permissions(administrator=True)
async def embed(ctx: commands.Context, *, text: str) -> None:
    embed = discord.Embed(title=ctx.author.name, description=text, colour=discord.Colour.random()).set_thumbnail(
        url=ctx.author.display_avatar.url)
    await ctx.send(embed=embed)
    await ctx.message.delete()
@bot.command()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(f"You do not have {commands.MissingPermissions.missing_perms} to run this command.")
#

it doesnt work

#

can anyone help

vocal snow
urban ingot
#

yall i made a antinuke w a usual 0.33-0.5 reaction

primal token
#

What?

urban ingot
#

yk what a antinuke is

primal token
#

Yes? Wdym by 0.33-0.5 reaction?

urban ingot
#

from when the event is called to when the member is banned

#

thats how long it took

primal token
#

What? nukes are arbitrary?

#

How do you know its a nuke or not with one event call?

urban ingot
urban ingot
primal token
urban ingot
primal token
#

Why would you use a whitelist?

urban ingot
#

trusted members..

#

other bots like Defender, summrs, are basically the same thing as mine 💀

primal token
#

The logic is quite funny imo

urban ingot
#

Ok

primal token
#

even if the member is trusted you cant measure the time of your bots reaction, just an average which you never said it was an average and where do these users get stored?

ivory pivot
#

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

primal token
#

And i wonder if automod will get new features like an antinuke which i wouldnt doubt that it wont come in the future

slate swan
#
class foo:
    def __init__(self):
        self.length = 1  # "self" represents the new instance of "foo" that was created.

    # self cannot be used here, you are creating a class, there is no "foo" class (it's being created) or instance of "foo" yet.
    length = 1  # this assigns "length" as a property to the "foo" class. this means foo.length is 1.
twin mantle
#

thats the point no im just really bad at explaining, ty

primal token
slate swan
#

not really

#

what do you think is more confusing then? i'm open to hear

primal token
#

All of it

slate swan
#

you can elaborate

primal token
#

self doesnt always represent a newly created instance, should explain it.

"self" represents the new instance of "foo" that was created.

I would use the word declaring and not creating as it may cause confusion, foo can be created inside of itself so there can be a foo inside of itself

self cannot be used here, you are creating a class, there is no "foo" class (it's being created) or instance of "foo" yet.

i'm pretty sure its not a property but a class variable

length = 1 # this assigns "length" as a property to the "foo" class. this means foo.length is 1.

slate swan
# primal token `self` doesnt always represent a newly created instance, should explain it. > # ...

self doesnt always represent a newly created instance, should explain it.
Given the __init__() method, that's inferred. I don't think __init__() would be used if a constructor wasn't intended.

I would use the word declaring and not creating as it may cause confusion, foo can be created inside of itself so there can be a foo inside of itself
Niche scenario, but valid point.

i'm pretty sure its not a property but a class variable
Sure, I could have worded that better. But "property" is just a broad term that also covers class variables. Please excuse my JavaScript exposure lol

valid void
#

Traceback (most recent call last):
File "main.py", line 5, in <module>
discord.ext.commands (command_prefix = "/")
TypeError: 'module' object is not callable

anybody know what i need to fix?

primal token
slate swan
#

While technically it's a variable, it's just not usually referred to as one.

primal token
primal token
slate swan
#

Convention, we don't call properties/attributes variables

pliant gulch
#

__init__ is 100% a constructor

#

It constructs the state of the class, basically 100% of the class

primal token
slate swan
#

Oh right, I totally forgot about that type

#

Never used it lol :P

primal token
slate swan
#

It's inferred as a class property

pliant gulch
#

It constructs the state

#

Otherwise you'd have a global state using only class attributes