#discord-bots

1 messages ยท Page 804 of 1

uneven apex
#

and it is giving this error

#
Traceback (most recent call last):
  File "D:\Python\lib\site-packages\discord\ext\commands\core.py", line 179, in wrapped
    ret = await coro(*args, **kwargs)
  File "d:\Coding Playground\Python\cwlbot\bot.py", line 191, in testing
    row = reps_sheet.find(tag).row  #getting row no
AttributeError: 'NoneType' object has no attribute 'row'

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

Traceback (most recent call last):
  File "D:\Python\lib\site-packages\discord\ext\commands\bot.py", line 335, in invoke
    await ctx.command.invoke(ctx)
  File "D:\Python\lib\site-packages\discord\ext\commands\core.py", line 916, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "D:\Python\lib\site-packages\discord\ext\commands\core.py", line 188, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'row'
#

but the tag i am passing in as argument is in the sheet

#

i am sorry for this spam but i am not find this is not working... it is really pissing me off lol

#

someone knows what might me causing ths?

nimble plume
quick gust
#

reps_sheet.find(tag) is apparently returning None

uneven apex
#

yes it is returning none

#

but i dont know why

quick gust
#

well the error is not there in the code you shared

uneven apex
#

umm yea i think the same

slate swan
#

getting this error. raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'somecommands' could not be loaded.

tender estuary
#

I use my brain to interpret python... normal interpreter is just too boring

vale wing
#

Hosting a discord bot using cognitive technologies would be fun

vale wing
slate swan
#

yes both in the same folder

vale wing
#

And your root folder is that

tender estuary
#

Used in event as a check for commands to work properly

vale wing
#

Afaik first the message goes to on_message event, then if you use process_commands on its context, its content will be checked if it is a command

#

And the corresponding function will be executed if there's such

kindred epoch
#

you can just use .listen() instead of .event

vale wing
#

^

#

You don't overwrite anything + there can be several listeners of one event

kindred epoch
#

on_message

vale wing
#

!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...
vale wing
#

There's a different decorator for using them in cogs

kindred epoch
#

you can use that anywhere, but for cogs its different

vale wing
#

!d discord.ext.commands.Cog.listener

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
vale wing
#

Yeah depends on your case

#

If it's not in cog, use listen, if it is, then commands.Cog.listener

#

Technically, you can put it to anywhere, but usually main.py only contains bot class and its runner

kindred epoch
#

ok. main.py is different than a cog file. In cogs you use commands.Bot.listener() and in main.py you can either use bot.event or bot.listen(), the reason i said bot.listen() is better than bot.event because you dont have to do the extra work and is more convenient

pliant gulch
#

bot.listen doesn't override the previous event callback

#

You only use commands.Cog.listener in a cog class because you don't have access to bot before the Cog is constructed

#

It's simply a marker, you'd use bot.listen where you have access to bot, you'd use commands.Cog.listener as a marker for places where you cannot

timid wagon
#

bot.event overrides the library's event itself, while bot.listen stacks over it. Simple as that.

#

commands.Cog.listener is just a version of bot.listen

pliant gulch
#

Straight forward as I can get, It doesn't override previous implementations

#

The previous implementation

#

If you use bot.event all previous implementations get wiped and it uses the new one you provided

#

For an example, with the commands extension. on_message has a default implementation

#

They hook onto on_message and process any commands with the parser, etc

#

If you use bot.event it overrides that with your new implemenation

timid wagon
#

I was just writing that out thonk I'll send it anyway

#

For example: when you use bot.event for on_message, it overwrites the lib's ability to process commands. Therefore you have to include await bot.process_commands at the end of it.

When you use bot.listen, is just stacks on the lib's event - it just adds onto it, doesn't overwrite it

pliant gulch
#

Yes.

timid wagon
#

In laymen terms, yes

pliant gulch
#

event clears ALL, Listeners keep default and keep any previous implementations you've made

#

It's literally just any new callback you set

#

No example is needed, just think about listener == no override

slate swan
#

you just change the decorator from event to listen()

#

or Cog.listener() if in a Cog class

timid wagon
unkempt canyonBOT
#

disnake/ext/commands/bot_base.py lines 600 to 601

async def on_message(self, message):
    await self.process_commands(message)```
timid wagon
#

When you use bot.listen, it'll not remove this, just stack on top of it

slate swan
#

event overrides the defaults, listen doesnt

timid wagon
#

^ can't make it simpler than that

slate swan
sick birch
#

Prefer listeners over events, you can have multiple different listeners listening for the same event, but you can't do the same with events. Also too many people use on_message event for some reason (youtube tutorial maybe?) then none of their commands work.

#

that's happened too many times to count

#

You don't need on_message

honest vessel
#

commands.comand is not an event

sick birch
#

^ it's how you make commands within a cog

honest vessel
#

so weird comparsion

sick birch
#

I think i get what he's saying

#

If you have command handlers there shouldn't be a need for on_message, is that what you're saying?

#

Don't get me wrong, on_message event does have some neat benifits

honest vessel
#

debug

sick birch
#

For example, if you wanted to ignore all messages from bots:

@bot.event
async def on_message(message: discord.Message):
  if message.author.bot:
    return

  bot.process_commands(message)
#

You could do the same with checks but I prefer this

#

Also if you wanted to have a feature where you have blacklisted users in a database

tender estuary
#

We could check if a message came from those users using on_message?

honest vessel
#

@sick birchor if you want to have your costume messages for when boosting server etc, message.type

sick birch
#
@bot.event
async def on_message(message: discord.Message):
  blacklisted_users = # get users from database
  if message.author.id in blacklisted_users:
    return
  bot.process_commands(message)
sick birch
#

No since that would still pass the message onto the command handler

#

Nope

tender estuary
#

commands would not work

sick birch
#

It would

#

it's a listener

#

not an event

tender estuary
#

It doesn't for me

#

Ok yeah

#

did not see that

honest vessel
#

but it tells you in doc, if i remember correct that they recommend use listeners

sick birch
#

Yep

#

It sort of acts like a gateway, that says what gets through to the command handlers and what gets dropped

#

Much harder yes

#

Well, on_interaction perhaps

honest vessel
#

but you can make a costume decoration check tho?

quick gust
#

global checks don't work on slash commands do they?

sick birch
honest vessel
#

@if_blacklisted

sick birch
#

Maybe the forks have that working, don't use forks wouldn't know

sick birch
quick gust
#

Oh

honest vessel
#

thanks robin ๐Ÿ™‚

sick birch
#

^ but yes you can make a custom decorator check as well

honest vessel
#

i always mix costum and custom

sick birch
#

they would both effectively do the same thing, i just prefer this since it's more straightforward

dire folio
#

i have this code to make a ticket transcript after closing a ticket

fileName = f"{ctx.channel.name}-transcript.txt"
        with open(fileName, "w") as file:
            async for msg in ctx.channel.history(limit=None):
                file.write(f"{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
        await ctx.channel.delete()
        ticketIds.remove(channelId)
        print(ticketIds)
        save_id()

and it gives me this

2022-02-05 16:57:39.978000 - Lord Cringey: $close
2022-02-05 16:56:13.451000 - Lord Cringey: Nothing happened
2022-02-05 16:56:10.380000 - Lord Cringey: As if
2022-02-05 16:56:08.040000 - Lord Cringey: So go about on ur day
2022-02-05 16:55:57.706000 - Lord Cringey: Just testing smth
2022-02-05 16:55:47.166000 - HC Utilities: 
2022-02-05 16:55:46.648000 - HC Utilities: @Lord Cringey @Staff

how would i make it so that the earlier msgs are at the top of the file and not at the bottom

sick birch
#

Anytime ๐Ÿ™‚

rustic onyx
honest vessel
#

one way could be put seek in or something @dire folio

rustic onyx
#

why my list isnt updating?

honest vessel
#

seek(0)

sick birch
#

pass in the oldest_first boolean

honest vessel
#

oh u even had that help ^

sick birch
#
async for msg in ctx.channel.history(..., oldest_first=True, ...):
  ...
dire folio
#

ty

timber matrix
sick birch
#

Any database is good

dire folio
#

also how would i round the time so it isn't so exact

sick birch
#

Personally the way I like to deal with databases is have a seperate API server, written in Express.js, which uses Prisma or TypeORM to interact with the database. Then in discord.py, you would use aiohttp to interact with the database.

honest vessel
sick birch
#

But of course to do that you'd need to know a bit of javascript

#

I think that heeds to the separation of concerns philosophy

dire folio
#

i use sqlite3

honest vessel
honest vessel
sick birch
honest vessel
#

you can also do str(time).split(".")[0] kek

sick birch
#

I think int() is more accurate. Say the UNIX timestamp says 2.518528, if you use round(), it would be 3, except you're still in the 2nd second, not the 3rd. int() would just return 2, which is accurate since you're in the 2nd second and not the 3rd

#

if that makes sense

#

Either way you'd be off by only a second but if you really need that accuracy use int() rather than round()

honest vessel
#

@sick birchthats true, round is round

dire folio
#

the accuracy doesn't matter too much

sick birch
#

You can also do math.floor(2.5827) which is the same thing as int()

honest vessel
#

i think most uses round atleast what iv seen

sick birch
#

yep shouldn't matter too much

#

int() and round() in this case do the same thing

honest vessel
#

if moneyprice round would be more accurate than int ๐Ÿ˜›

quick gust
sick birch
#

Well it indicates the time better, since it doesn't round up

honest vessel
#

cant you tell round to round down tho?

ebon fox
#

Hey any hosting recommendations for free (or cheap ones) that are reliable

sick birch
ebon fox
sick birch
#

You can chain except statements:

try:
  # something
except error1:
  # print error1
except error2:
  # print error2
except error3:
  # print error3
sick birch
#

You can do one of 2 things:
i) remove all try/excepts and stress test your code, and see all the possible errors that could happen
ii) go searching around documents for all functions that you use and see what errors they can throw

maiden fable
#

Tbh I would love to see someone make an economics bot yk

honest vessel
sick birch
#

For example, say you had await ctx.send(...) in your try block, according to the documentation, it can raise 1 of 3 errors:
i) HTTPException
ii) Forbidden
iii) InvalidArgument
You can chain 3 except statements for each of these, and do something according to those errors

fallen mica
sick birch
quick gust
fallen mica
quick gust
#

why are you getting the guild? member.guild returns the guild object iirc...?

#

you can just do server = member.guild

sick birch
#

Yeah member.guild returns the guild they just left

#

and you can leave out the user since it's just re-getting it

#

or do user = member if you want to

quick gust
#

I just found it strange you used the guild object's id attribute to get the guild object kekw

sick birch
#

it happens

quick gust
#

especially with newbs like me

sick birch
#

and if you're looking for a channel named general, easiest way would be to use utils.get() rather than find

#

you don't need to use lambda for that

gusty hatch
#

Lol

sick birch
#

But yeah I don't really think there's a better way of doing what you have right now without changing the way it works (user defined join/leave channel)

honest vessel
#

maybe use elif and save on all returns

quick gust
#

would that really make it cleaner though?

honest vessel
#

last return has nothing impact aslong u dont have more codes belows it

honest vessel
slate swan
#

bot.py

from discord.ext import commands
from dotenv import load_dotenv
from os import getenv
import discord

load_dotenv() # You can pass the location of the .env file if it's not in a standard location

token = getenv("DISCORD_TOKEN")

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

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

bot.load_extension("somecommands") # Note, we don't need the .py file extension

bot.run(token)

somecommands.py

from discord.ext import commands # Again, we need this imported
import discord
import time
from datetime import datetime

class SomeCommands(commands.Cog):
    """A couple of simple commands."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        self.last_msg = None

    
    # Embded message command shows the embded info
    @commands.command()
    @commands.has_role("Admin")
    async def hello(self, ctx: commands.Context, productname):
        
        embed = discord.Embed(title=test, url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
        embed.set_author(name="something", icon_url="https://avatars.githubusercontent.com/u/16879430")
        embed.add_field(name="Field 3", value="Look I'm inline with field 2!", inline=True)
        embed.set_footer(text="Powered by United Digital Company!", icon_url="https://cdn.discordapp.com/emojis/754736642761424986.png")

        await ctx.send(embed=embed)

def setup(bot: commands.Bot):
    bot.add_cog(SomeCommands(bot))

call.py

import bot
from somecommands import SomeCommands, hello

text = ("Hello world!")

if "equal" == "equal":
    sent = hello(text)
    sent()

In the call.py i would like to call the function in somecommands to sent a embded message. And use the variable from call.py

sick birch
#

No you can use elifs and get rid of the returns

honest vessel
#

if a==1:
...
if a===2:
....

better with ```py
if a == 1:
...
elif a == 2:
...
else:
...

kinda but u can skip else if no need
#

else will be if any other statement above matched it will be executed

manic wing
#

why get rid of the returns lol

#

return > elif

honest vessel
#

huh?

slate swan
#

pls help i have error in my bot music cmd

sick birch
#

it's all the same and subjective, some people like to use returns some like if/elifs. they do the same thing

sick birch
slate swan
#
An error occurred: Command raised an exception: ClientException: ffmpeg was not found.```
manic wing
#
def func(num: int) -> bool:
  if num == 0:
    return False
  return True
``` this is much better than using `elif`
slate swan
#

๐Ÿ‘

honest vessel
#
  if server.system_channel:
    await server.system_channel.send(msg)
    return

  general = find(lambda x: x.name == 'general',  server.text_channels)
  if general and general.permissions_for(server.me).send_messages:
    await general.send(msg)
    return

  backup = server.text_channels[0]
  if backup and backup.permissions_for(server.me).send_messages:
    await backup.send(msg)
    return
  return
  if server.system_channel:
    await server.system_channel.send(msg)

  general = find(lambda x: x.name == 'general',  server.text_channels)
  elif general and general.permissions_for(server.me).send_messages:
    await general.send(msg)

  backup = server.text_channels[0]
  elif backup and backup.permissions_for(server.me).send_messages:
    await backup.send(msg)
manic wing
#

you can just do return await backup.send(msg)

honest vessel
#

but that general variable should be run first

manic wing
#
if server.system_channel:
  return await server.system_channel.send(msg)

general = find(lambda x: x.name == 'general',  server.text_channels)
if general and general.permissions_for(server.me).send_messages:
  return await general.send(msg)

backup = server.text_channels[0]
if backup and backup.permissions_for(server.me).send_messages:
  return await backup.send(msg)
honest vessel
#

yeah that could work too

#

i guess its a taste decision

#

that one does look clear n easy to read

#

oh well atleast we teached him elif ๐Ÿ˜›

#

if, elif, else is what exists

dire folio
#

how would i increase the font size when typing into a file

honest vessel
#

that has nothing todo with this channel sorry

#

but try CTrL+ (+sign)

dire folio
#

i meant like with the bot

honest vessel
#

u cant edit fontsize?

dire folio
#

cause i need it to right into a file

honest vessel
#

am lil bit confused

dire folio
#

nvm

quick gust
#

either I'm not understanding your question or you are using Microsoft Word

manic wing
#

tbh there should hardly ever be a reason to use elif

honest vessel
manic wing
#

yes really

honest vessel
#

nope

#

say u make a game, and wanna grab key pushed

manic wing
#

!ot

unkempt canyonBOT
honest vessel
#

it would be ugly with only ifstates n not have a elif - and u missing out else

#
if a == b:
...
elif a == c:
...
else:
   ....

vs

if a == b:
 ...
if a == c:
 ...
``` now u have no else
maiden fable
#

Suppose u r doing it in an error handler and the command is raising both HTTPException and ChannelNotReadable due to any reason. Then both the if statements will execute

#

Happened with me a few months ago

pliant gulch
#

You would fix that by using isinstance

#

Doesn't make sense eitherway to check if an instance is another instance with == anyways

#

You'd use is

maiden fable
#

If I remember correct, it still errored out

maiden fable
#

Yups

#

I used simple ifs

pliant gulch
maiden fable
#

Just an example

honest vessel
#

but also one error is an error

#

when u fix first it would land on elif is error there

#

but i can see if u use only if it will hint both errors

#

oh well if no returns ๐Ÿ˜‰

#

does py3 have case match yet?

devout iris
#

Let's say I have a command that automatically sends a message to a channel at a certain time interval, and when the user sends the word I want to the channel, how can I stop the command without restarting the bot?

honest vessel
#

you can basicly make a a varaible you can give true of false

#

and have that send message function check if that var is true or false first

maiden fable
honest vessel
#

like .announcement (will turn False if var is True, and True if False)

#

and ur automaticly event, checks that var

#

that way u can turn off n on

honest vessel
devout iris
honest vessel
#

@maiden fablekinda weird tho why so late with it when C/C++ and php all had it centries ago

pliant gulch
#

python moment

pliant gulch
#

If you really want you can make your own case and match with a class implementing __exit__ and __enter__ along with __call__

#

Should be fairly easy to do

honest vessel
#

or u can just do if and ifelse ๐Ÿ˜›

#

just wondering why taken so long time to get that

strong vessel
#

my discord bot looks like it processes one message at a time, it does not want to process stuff in parallel. is there some super easy way to make it process messages in parallel?

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    elif message.content.startswith('!something'):
        query = message.content
        response = f(query)
        await message.channel.send(response)
honest vessel
#

process_command()

strong vessel
#

right now it will wait for all the queued messages to be fully answered before it dumps all the queued responses at once. so it is inefficient and waste of time

#

i don't get it

strong vessel
honest vessel
#

@strong vesselyeah if u put await process_commands(message) at end of ur on_message

#

but that usally needed to process commands, i dont know what ur issue is about it should be asyncronised

strong vessel
#

ok

honest vessel
#

do u mean command snot working?

strong vessel
#

i mean if it suddenly dump 10 messages on it, instead of doing it all in parallel, it would queue the 10 messages, processing 1,2,3,4,5 ... 10 in sequence one by one, and then it would dump the 10 responses (5 messages/5seconds) to the user

honest vessel
#

cause u uses on_message instead of doing commands functions

#

is my guess

strong vessel
#

what i want is for it to try everything in parallel not in sequence, and of course not to wait for previous things to be done

honest vessel
#

your on_message clogging up perhaps

#

try learn make commands. esp cogs and skip use startwith in on_message for commands

honest vessel
honest vessel
#

or mixing nonasyncronized libs n codes with asyncronized (discord)

#

even if u make a command that is not asyncronized it will act same as for u now clogging up

strong vessel
#

i think its definitely my discord logic that is forcing synchronous

#

since i checked the other aspects and they are fully parallel/async

honest vessel
#

the startwith is kinda cheap way of make commands

#

should't be used

sick birch
#

if you block the event loop discord.py won't be able to heartbeat to the gateway and you're gonna get disconnected

strong vessel
#

i don't understand half of this tbh

#

don't mean to be cringe but its my first bot

honest vessel
#

@strong vesseltheres plently of examples of basic bot structure with cogs n commands

dire folio
#

I have this for a ticket transcript

cday = datetime.now().strftime('%a')
    cdate = date.today().strftime("%b %d, %Y")
    ctime = datetime.now().strftime("%H:%M:%S")
    current = f'{cday} {cdate} {ctime} '
    if channelId in ticketIds:
        fileName = f"{ctx.channel.name}-transcript.txt"
        with open(fileName, "w") as file:
            file.write(f"Ticket Name: {ctx.channel.name}\n\n")
            async for msg in ctx.channel.history(limit=None, oldest_first=True):
                file.write(f"{msg.author.display_name} >>> {msg.clean_content}\n")
                file.write('\n')
                num = num + 1
            file.write(f'Generated by HC Utilites\nTime: {current} GMT+0000\n(Greenwich Mean Time)\nNumber of messages: {num}')

how would i make it so if a message is an embed it will write Message cannot be displayed to the file

honest vessel
#

@strong vesselnothing is cringe being new.

strong vessel
#

oh i guess process command

honest vessel
#

process_commands() only passes it throu, but what uu should is make commands as methods

slate swan
#

Use the commands.Bot class instead of discord.Client

#

it allows you to make commands with Functions

honest vessel
#

and its way more effeciant than read line by line and execute ifstatements in on_message

slate swan
slate swan
slate swan
honest vessel
#

he has a cog tho

#

i just dont understand what that third file gonna do

slate swan
honest vessel
#

also this looks beoken af, if "equal" == ""equal:

honest vessel
#

its equal

slate swan
#

fixed

#

whatever is an example XD

honest vessel
#

tonny what are u tyring to do

#

u wanna send an emebed from a new file?

#

why dont u send it in ur cog that u already has

#

i am so confused man maybe u thinking wrong of what u wanna do

#

what u can do is in ur cog, is import ur functions from the file

#

and have it return

#

into your cog calling ur functions

errant quiver
#

yo how do you incorporate your python code into a discord bot

honest vessel
#

by implament the code u want?

#

and rewrite functions

errant quiver
honest vessel
#

@final ironi guess its saturday ๐Ÿ˜„

slate swan
honest vessel
final iron
errant quiver
honest vessel
#

ctrl+c ctrl+v

errant quiver
honest vessel
final iron
#

Takes you through the entire process

leaden hollow
#

so which is the best fork for dpy now?disnake?

honest vessel
slate swan
honest vessel
#

based if someone makes a fax-machine that can take writting n scans n return code

#

handwritten bot

#

litterly

pliant gulch
#
repl.it

Repl.it is a simple yet powerful offline IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin (beta), QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Python 2.7, Ruby, Roy, Python, Nodejs, Go, C++, C, C#, F#, HTML, ...

honest vessel
#

make sure to put settings in folder (windows) show file extantions and name em .py

leaden hollow
slate swan
#

just use find and replace which most editors have and replace the name space discord to disnake or import disnake as discord

stone beacon
slate swan
#

any1 know how to add this button to bot?

#

not as a status

leaden hollow
errant quiver
#

what editor do you guys use

leaden hollow
#

in discord devportal

slate swan
#

it auto adds after i set this?

leaden hollow
#

yes

slate swan
#

okay thank you

leaden trench
errant quiver
leaden hollow
leaden trench
#

well i use vscode

errant quiver
leaden trench
errant quiver
final iron
leaden hollow
#

for discord bots I don't think there's a need of pycharm tbh

final iron
#

Pycharm is a full on ide while vscode is more of a text editor

leaden hollow
leaden trench
errant quiver
leaden trench
errant quiver
final iron
slate swan
errant quiver
slate swan
#
    @commands.Cog.listener()    
    async def on_message(self, message):
        guild = message.guild
        if message.content == "citizenship":
        #all citizenships citizenships
            role1 = guild.get_role(938834958124978247)
            role2 = guild.get_role(938834984515555458)
        #
            list_of_roles=[role1, role2]
            citizenship=random.choice(list_of_roles)
        #gce = grant citizenship embed
            gce=discord.Embed(title="Congratulations", description=f"You have been granted {citizenship.mention} citizenship", color=0x4da917)
            citizenshipdenied=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {role1} citizenship.", color=0xff0000)
            citizenshipdenied1=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {role2} citizenship.", color=0xff0000)

            if role1 in message.author.roles:
                return await message.channel.send(embed=citizenshipdenied)
            elif role2 in message.author.roles:
                return await message.channel.send(embed=citizenshipdenied1)
            else:
                await message.author.add_roles(citizenship)
            await message.channel.send(embed=gce)```
#

Yhis was working not even yesterday

#

Today it isn't working anymore. How.

slate swan
vale wing
fresh steppe
#

Can someyeone help me? When i make a discord bot, or even copy the code (not forgeting to change the token) it Just doesnt do antthing, i whatched some tuturials but they Just al say that it must to work? I use pycode btw.

vale wing
short zinc
#

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

short zinc
#

read this and paste your code in the link โ˜๏ธ

sick birch
#

and discord.py is not beginner friendly, you need to have a firm understanding of the language before you use the library

slim ibex
#

^

short zinc
#

instead tell them to not watch outdated tutorials

slim ibex
#

but then just copy code?

short zinc
vale wing
hoary cargo
slim ibex
#

The docs gives you the functions and what said arguments are so you can use them for yourself

#

itโ€™s not a whole bot that they give you

short zinc
#

I am just saying that docs don't suit people who are just getting into coding

vale wing
#

Copying code won't teach you anything unless you understand what does each line of that code do

slim ibex
#

^

#

youโ€™ll have to learn to read docs eventually also

vale wing
short zinc
#

it is.

fresh steppe
#

Import discord

TOKEN = "the token"

client = discord.Client()
@client.event
async def on_ready()
print("logged in") #this doesnt even halen

client.run(TOKEN)

slim ibex
#

no it ainโ€™t lmfao

vale wing
#

Yeah as expected

#

He's completely new to python as it turns out

slim ibex
#

lmfao

fresh steppe
slim ibex
#

everyone knows you use bot over client๐Ÿ—ฟ

vale wing
#

@fresh steppe we strongly recommend you to learn some basics of python, it will be much better for you. We can fix this code of course, but this won't give you any knowledge and you will not be able to make one by yourself

slim ibex
#

^

short zinc
manic wing
#

dude his name is hacker

#

hes a god at every language

slim ibex
#

Lmfao

fresh steppe
#

Lol

manic wing
#

he makes nukes on the daily

slate swan
slim ibex
#

๐Ÿ’€

fresh steppe
#

Ok i wil look on some simpler projects

vale wing
#

Yeah

slate swan
strong vessel
#

I rewrote my code but it still does not run in parallel. It waits for every received message to be done before dumping them all at once to the users.

from discord.ext.commands import Bot

bot = Bot("!something")

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    else:
        query = message.content
        response = f(query)
        await message.channel.send(response)
    await bot.process_commands(message)
#

how to make it run in parallel? and to send the response the moment it is done instead of waiting for all the others to be done?

#

like how to make every message immediately start processing, and then respond as quickly as it is done, never waiting

pliant gulch
#

What ever f is, it isn't allowing for concurrency

#

You probably have a bunch of blocking code in there

strong vessel
#

It's just requests.request

final iron
#

That's blocking

vale wing
#

๐Ÿ˜ณ

final iron
#

You should be using aiohttp

wide shale
#

How do I make my own bot go online

strong vessel
#

oh no

vale wing
#

Aiohttp good ๐Ÿ‘

strong vessel
#

wow i hope this works

manic wing
slate swan
#

i remember when i thought this was #bot-commands and i posted a command here and everyone was like "i hate you go to hell"

hoary cargo
slate swan
wide shale
#

How do I get my bot to be online

slate swan
final iron
slate swan
#

i deleted it afterwards

#

or i was using an alt

final iron
#

Mhm

hoary cargo
slate swan
#

honestly if you're no longer only using if statements, it means you're now a better programmer then someone whos been making a game for like 10 years

unkempt canyonBOT
maiden fable
#

๐Ÿ‘€

slate swan
slate swan
slate swan
maiden fable
unkempt canyonBOT
slate swan
strong vessel
#

thanks, replacing requests with aiohttp was perfect

slate swan
#

hi i have this issue when i add f before command description its no longer seen as command desc

#

i mean when i make it f string

manic wing
#

show code

slate swan
#

i mean this ```py
@commands.command()
async def roll(self, ctx: commands.Context, dice: str):
f"""Rolls a given amount of dice in the form \d\

    Example:
    ```
    {ctx.prefix}roll 2d20
    ```
    """
#

i want this to be current prefix but when i add f string its no longer seen as desc

#

top is with f string

manic wing
#

i see - docstrings cant really have f strings considering the variables havent been declared - instead you can use {} and .format

slate swan
#

inside of a string?

manic wing
#

!e py string = "hello {}" print(string.format("Fred"))

unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

hello Fred
slate swan
#

did that and doesnt work

#

did like this ```py
"""Rolls a given amount of dice in the form \d\

    Example:
    \`\`\`
    {}roll 2d20
    \`\`\`
    """.format(ctx.prefix)
manic wing
#

no

#

in the help command you use the format

slate swan
#

oh okay

vapid anchor
#

you can keep the {ctx.prefix} syntax

#

it works with format too

#
>>> user = Mock()
>>> user.name = "dave"
>>> "hello {user.name}".format(user=user)
'hello dave'
slate swan
#

i think i did something wrong

kind path
#

does anyone know a good tutorial for a python economy bot that works with replit?

sick birch
#

Tutorials for discord.py are are outdated and are quite useless, you're better off reading the docs and the github examples

#

Also replit ๐Ÿ˜ฌ

kind path
sick birch
#

And for good reason :p

neat tartan
#

Replit is unintentional beginner bait

sick birch
#

Not to mention it's garbage

#

Which is as mild as I can put it

#

There are a bunch of really awesome editors, pycharm, vscode, atom, whatever you want that you can use instead of replit

neat tartan
#

Vscode is fairly common for new coders

sick birch
#

Yep, it's a very good tool for both beginners and experts alike

slate swan
#

thats the code ```py
for file in os.listdir("modules"):
if file.endswith(".py"):
bot.load_extension(f"modules.{file}")

analog nova
#
    @commands.Cog.listener()
    async def on_dbl_vote(self, data):
        member_id = data["user"]
        channel = self.bot.get_channel(882354495466663936)
        reward = random.randint(800, 1000)
        await channel.send(f"<@{member_id}>, you have earned {reward}$TPET from voting on top.gg! Thank you! (Dev info: {member_id})")
        await ecomoney.update_one({"id": member_id}, {"$inc": {"bank": + reward}})
#

won't add the reward to the database

honest vessel
#

@slate swan the module not found error x

#

maybe uhave files there

#

thats not cogs

slate swan
#

every file in this folder is a cog

honest vessel
#

@slate swan well module not found

#

wait_for()

slate swan
#

is it correct? py guilds = await cluster.find() for x in guilds: channel = x["channel"] c = client.get_channel(channel) await c.send("Test")

#

how do I make my bot give a certain role?

rocky trench
#

anyone here with a bot on discordbotlist? If yes, how do I get the webhook to work?

rocky trench
#

it doesnt post anything on upvotes

slate swan
#

well, I can't help

rocky trench
#

what is a 'webhook secret'

slate swan
#

i think

rocky trench
#

sooo what do I add there

#

i got no idea how to get it

slate swan
#

idk

strong vessel
#

why does 1 application have multiple bots?

rocky trench
strong vessel
#

i didn't understand it, because when you invite the bot, it uses the application ID, but the application can have multiple bots. and each bot has its own token. does this mean that actually you can invite a whole bunch of bots in one go? so its like a giant bundle of bots?

#

but none of the bots seem to use that

#

oops nvm its a one to one thing

sick birch
#

One application can have one bot, one oauth2, etc

manic wing
#

whats oauth2

slate swan
#

how do I add slash commands to my bot

pliant gulch
#

I do recommend reading the RFC, good knowledge to know

manic wing
#

is it the thing websites can use to let people log in with their discord account

pliant gulch
#

Yes

manic wing
#

oh right

#

is it just a link or smtijn

sick birch
#

actually working with it right now ๐Ÿ˜‰

strong vessel
#

nvm

#

looks different

sick birch
#

on_interaction does pick up those so it's worth keeping in mind

slate swan
#

oh

#

what do i fork?

sick birch
#

Pick one of the existing ones

#

Or go with a different library

#

Pycord, disnake, nextcord, hikari are the ones i've heard of

slate swan
#

ok

winged mural
pliant gulch
#

Crazy how one wrapper archived and now we got the warring states

strong vessel
#

why did it ever archive though

pliant gulch
#

Maintainer wasn't happy

sick birch
#

Massive gist page on it

#

Anyone have the link to it?

pliant gulch
strong vessel
#

its fine i googled it

sick birch
#

^

strong vessel
#

oh nice

grand shell
#
@slash.slash(description="test")
async def hi(ctx: SlashContext):
    await ctx.send("yooo")

hey, im trying to make a slash command but it never actually responds. it just says interaction failed every time

vale wing
#

It doesn't get registered at time most likely

grand shell
#

so how can i fix it?

vale wing
#

What library do you use?

grand shell
#

discord-py-slash-command

vale wing
#

Uh

#

Why not a fork of dpy?

#

They are better

grand shell
#

does pycord have it with it?

vale wing
#

I think it does

grand shell
#

oh cool

vale wing
#

But personally I can't help with it

scarlet aurora
#

how do i take off default HELP command on my bot?

vale wing
#

Afaik most of forks have the test_guilds param in bot constructor, use it or its alternative depending on lib

vale wing
scarlet aurora
#

bot constructor is where?

vale wing
#
bot = commands.Bot(..., help_command=None)```
scarlet aurora
#

bot = commands.Bot(command_prefix=">" help_command=None)

#

like this?

#

i forgot the comma

hushed field
#

you should subclass your help command, not make a custom one

scarlet aurora
vale wing
hushed field
#

9/10 to make a "better" one

hushed field
#

!help <command/cog/group/None

vale wing
scarlet aurora
#

i prefer just removing it and then remaking the help command

hushed field
#

why though? its easier

#

just take 5 minutes and read this and try it out

slate swan
#

hi i wanted to create event that does stuff on guild join but in a cog how can i make it since this doesnt work ```py
@commands.event
async def on_guild_join():
pass

sick birch
sick birch
vale wing
#

Isn't it commands.Cog.listener()?

pliant gulch
sick birch
#

Oops yeah

slate swan
#

listener?

#

okay

#

cause there is no .listen

sick birch
#

Yeah got it confused with bot.listen

vale wing
#

!d discord.ext.commands.Cog.listener you can find examples of usage here

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
pliant gulch
#

Man do I hate how discord.py does event's/listeners

slate swan
#

ty

vale wing
#

Nvm you can't

#

Only in bot listen

slate swan
sick birch
pliant gulch
vale wing
#

Some libs just have enums containing events

pliant gulch
#

Yea this ^

#

Discord.py using literal strings mean no auto suggestion from your IDE

pliant gulch
slate swan
#

hey also one small question how can i get joined guild id from on_guild_join listener?

vale wing
#

member.guild.id

scarlet aurora
#
@bot.command()
async def help(ctx):
    embed = discord.Embed(
        title=f"",
        description=f"",
        colour=0x3D9AF2)

    await ctx.send(embed=embed)``` why wont this work?
pliant gulch
#

As this event provides the discord.Guild object for you

sick birch
vale wing
scarlet aurora
#

ik i have it

sick birch
#

and yeah there's already a help command built in

scarlet aurora
#

cuz built in help command i don't like

#

i already did help_command=None

sick birch
#

you can customize how it looks by subclassing

#

rather than making your own from scratch

slate swan
#

!d nextcord.Guild

unkempt canyonBOT
#

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

This is referred to as a โ€œserverโ€ in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guildโ€™s hash.

str(x) Returns the guildโ€™s name.
pliant gulch
#

Otherwise use a zero width character, E.g \u200b

#

Or ** ***

cedar stream
pliant gulch
#

Brandons cat โค๏ธ

slate swan
#

oh hi andy

#

long time no see pithink

weary gale
#

how would i ping a user?

#

using their id

slate swan
hushed field
#

get the user/member then object.mention or just f"<@{id}>"

weary gale
#

thanks

slate swan
#

!d discord.Member.mention | just get_member(id) and it will return a discord.Member instance

unkempt canyonBOT
slate swan
#

show code

#

you did something wrong

weary gale
#

wait im using discohook rn

#

not in vsc

hushed field
weary gale
#

just a webhook embed

weary gale
#

tyvm

slate swan
#
Ignoring exception in command prefix:
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\testing\modules\config.py", line 29, in prefix
    await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id))
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
ValueError: parameters are of unsupported type

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type

i get this error

#

guild_id is not INTEGER

#

so what is it

#

idk

#

check your db

#

i mean in my db it is int

#

screenshot

hushed field
#

sql dbs need precise data

slate swan
#

i can send you my command

#

thats this command ```py
@commands.command()
async def prefix(self, ctx, prefix: str = ""):
if not prefix:
return
async with aiosqlite.connect("data.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
print(data)
if data:
await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
else:
await cursor.execute("INSERT INTO prefixes (prefix, guild_id) VALUES (?, ?)", (prefix, ctx.guild.id))
await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id))
data = await cursor.fetchone()
if data:
await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
await ctx.reply("Changed prefix from")
else:
return
await db.commit()

slim ibex
#

you dont need async with db.cursor

slate swan
#

i can use cursor = db.cursor?

#

he does..?

#

i thought i need it

slim ibex
#

no. you can just use db.execute from the connect

#

that works also i believe

slate swan
#

well ill just leave it like that since it worked

slim ibex
#

ye all good

#
async with aiosqlite.connect(...) as db:
    await db.execute("INSERT INTO some_table ...")
    await db.commit()

this is straight from the docs

slate swan
#

okay but why my code doesnt work ๐Ÿ˜ข

slim ibex
#

any errors?

slate swan
slim ibex
hushed field
#

most help commands with slash are fucked

slim ibex
#

true

slate swan
#

it says object dict cannot be used in an await expression

#

for this line

fervent shoal
#

for a detect and respond code, how would it be

hushed field
#

dont await it

slate swan
#

okay

slate swan
fervent shoal
#

is this remotly right

slate swan
hushed field
slate swan
#

in @client.event

hushed field
fervent shoal
#

oh i

hushed field
slate swan
#

its ah

#

quite long

small summit
#

how can i make a program search a specific string and download the first corresponding google image, or copy the link so it can be embedded into something like a discord embed? most of the web scraping stuff doesnt work on my mac so it's hard to test

slate swan
#

il send the first half

fervent shoal
#

am looking for help

slim ibex
#

wtf

slate swan
#
@client.event
async def on_message(message):
    if not isinstance(message.channel, discord.channel.DMChannel):
        keys = db.keys()
        guild_id = str(message.guild.id)
        prefix = await get_prefix(message.guild.id)
        if message.author == client.user:
          return
        elif message.author.bot: 
          return
        elif "discord.gg/" in message.content.lower() and get_antiInvites == True and message.author.guild_permissions.administrator == False or "discord.com/invite/" in message.content.lower() and get_antiInvites == True and message.author.guild_permissions.administrator == False:
            await message.delete()
      
            ni = discord.Embed(color = 0xe74c3c, description = f":mfailed: {message.author.mention}, no invite links allowed!")
            
            await message.channel.send(embed = ni)

            guild_prefix = await get_prefix(message.guild.id)
            prefixLength = len(guild_prefix)
            if message.content.lower()[0:prefixLength] == guild_prefix:
                msg = "-" + message.content[prefixLength:len(message.content)]
                await client.process_commands(msg)
final iron
slim ibex
#

he has arrived!

fervent shoal
#

theres something before the first line

#

but i tried a few things but got the yellow or red lines

slim ibex
#

but the code still isn't right

slate swan
#

for whos code is this

final iron
slate swan
#

should learn oop and python

fervent shoal
#

thats what i need help with

slate swan
#

@hushed field also if i don't "await" it then it just adds another field to the collection

fervent shoal
#

something to detect lfg

final iron
#

What is lfg

fervent shoal
#

it stands for looking for group

#

need something to detect that and respond with a gif

#

jus need the detector part

final iron
#

So then just add an if statement

#

if lfg in message.content:

slate swan
fervent shoal
#

well shit

slate swan
#

!e

a = ("not, a, tuple")
b = ("a", "tuple")
print(a)
print(b)
unkempt canyonBOT
#

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

001 | not, a, tuple
002 | ('a', 'tuple')
fervent shoal
#

ohhh

slate swan
#

you should learn dpy

cold sonnet
fervent shoal
cold sonnet
fervent shoal
#

ok i know i suck at this

slate swan
cold sonnet
#

had you tried learning it before doing it, it would look much better

fervent shoal
#

how do i fix defining message, and ctx, ctx was used earlier and worked perfectly fine

slate swan
#

guys just spoonfeed tbh

cold sonnet
#

async def on_message stuff comes directly after the decorator

#

and the if statement's gonna be within that

final iron
cold sonnet
#

since you don't have a context in an event, you wouldn't use it

#

so replace ctx

#

with message.channel

#

because you have a message once defining a function correctly

slate swan
cold sonnet
#

how'd you define message

slate swan
final iron
fervent shoal
#

thank you so much ๐Ÿ™

final iron
#

Spoon feeding at its finest

slate swan
cold sonnet
slate swan
#

oh

final iron
cold sonnet
#

process_commands doesn't take a string

final iron
#

ยฏ\_(ใƒ„)_/ยฏ

slate swan
#

so what do i do???

slate swan
cold sonnet
#

process_commands takes just the whole message object

slate swan
#

and when i define client

#

client = commands.Bot(command_prefix = "e", intents = intents, case_insensitive = True)

#

i can't do get_prefix because it requires a guild id

cold sonnet
#

so?

#

what's wrong with the id

slate swan
#

im not sure how i'm supposed to define it

#

client = commands.Bot(command_prefix = get_prefix, intents = intents, case_insensitive = True)

#

like that?

fervent shoal
#

why is this happening, never happened before

cold sonnet
#

yeah, and get_prefix is a function returning the correct prefix for that specified guild_id

final iron
#

ยฏ_(ใƒ„)_/ยฏ

slate swan
cold sonnet
#
def get_prefix(ctx):
    if ctx.guild.id == 6874894524:
        return "!"
#

I think it's like that, I'm not sure how get_prefix gets the context

slate swan
#

that is my get_prefix

cold sonnet
#

well

fervent shoal
#

why is it doing this when i run it without debugging

cold sonnet
fervent shoal
#

oh shi

slate swan
cold sonnet
#

yeah you don't use that because...?

final iron
#

Can someone explain something to me? If you do:

bot = commands.Bot(prefix=get_prefix)

get_prefix has access to bot and discord.Message

#

But you're not calling the function get_prefix

slate swan
#

async def get_prefix(ctx)

final iron
#

So how does it even get called?

cold sonnet
#

def get_prefix(client, message): ##first we define get_prefix

#

so client replaced with bot

slate swan
#

okay

cold sonnet
slate swan
#

okay

#

so when i call it

#

i just do get_prefix(ctx.message)?

cold sonnet
#

no, you don't call it yourself

slate swan
#

alright

cold sonnet
#

you just pass it to your bot's prefix kwarg

slate swan
#

so to get a prefix somewhere else

#

i use my original

#

and then i create another one?

cold sonnet
#

well how you change and store your prefixes is your own choice

#

this tells you to use json, but just use a database

slate swan
#

alright thanks

slate swan
cold sonnet
#

yeah

#

docs show it doesn't even take bot

slate swan
#

thanks

fervent shoal
#

Traceback (most recent call last):
File "C:\Users\W\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\E\riot bot 5, no way this works.py", line 70, in on_message
if lfg in message.content:
TypeError: 'in <string>' requires string as left operand, not tuple

#

so the string was wrong

#

and my monke brain is not working

cold sonnet
#

if you'd name it something else, it wouldn't even work

unkempt canyonBOT
#

discord/ext/commands/bot.py line 904

async def get_context(self, message: Message, *, cls: Type[CXT] = Context) -> CXT:```
cold sonnet
#

it's there yert

#

no, wrong one

unkempt canyonBOT
#

discord/ext/commands/bot.py line 866

async def get_prefix(self, message: Message) -> Union[List[str], str]:```
cold sonnet
#

it's there yert

fervent shoal
#

if lfg in message.content:
TypeError: 'in <string>' requires string as left operand, not tuple

so if i understand this correctly, the in message.content is messed yup

cold sonnet
#

no

#

you didn't understand this correctly

fervent shoal
#

understandable

cold sonnet
#

you can't just
if every chips in can of pringles

fervent shoal
#

how do i leave string as operand instead of a list

#

cuz thats what a tuple is?

cold sonnet
#

go through the list and check every string in it

cold sonnet
fervent shoal
#

lfg=("lf1m", "lf2m", "lf3m", "lf4m", "lf5m", "lf1", "lf2", "lf3", "lf4", "lf5", "lfg", "lf")

#

this one?

cold sonnet
#

yeah, go through it with a for loop

fervent shoal
cold sonnet
#

without even thinking about it

#

you can do it

fervent shoal
#

i am thinking how to do that

#

can i tho

slate swan
cold sonnet
#
for i in lfg:
    if i in message.content:
        #something's in it, stop and do something
fervent shoal
cold sonnet
slate swan
#

๐Ÿšช๐Ÿšถ

fervent shoal
#

ok so it works

#

but it keeps on spamming it

final iron
fervent shoal
#

make fun of me rn

#

get it all out

slate swan
fervent shoal
#

yea

fervent shoal
cold sonnet
slate swan
fervent shoal
#

how do i fix >.<

slate swan
#

its in a for loop so for each element it will send that

fervent shoal
#

return

slate swan
#

!e

for a in range(1, 10):
    print(a)
unkempt canyonBOT
#

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

001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
cold sonnet
#

okimii

slate swan
#

?

cold sonnet
#

that was a really bad example

slate swan
#

๐Ÿ˜”

fervent shoal
#

return what

cold sonnet
fervent shoal
#

what am i returning

slate swan
cold sonnet
#

that was a wise example

slate swan
slate swan
cold sonnet
#

!resources Riot

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.

fervent shoal
slate swan
cold sonnet
fervent shoal
#

the first await?

slate swan
#

yes

cold sonnet
#

and indent it

#

the second one

fervent shoal
#

to match the if statement?

cold sonnet
#

and remove (message) there

cold sonnet
fervent shoal
#

can i restrict what channel it cannot go in

cold sonnet
fervent shoal
#

correction, how do i restrict it

cold sonnet
#

check for example for the message's channel's id

fervent shoal
#

if channel(channel),

cold sonnet
fervent shoal
#

you are speak big words wise one

cold sonnet
#
if message.category.id == *some big numbers*:
    return
fervent shoal
#

and then

#

i want to stop it from the catagory

cold sonnet
#

get category's id by enabling developer mode on discord, right clicking the category in discord and copying id

#

and then replace some big numbers with that

fervent shoal
#

yes

#

and then if its that, no message sent is waht im tryna do

cold sonnet
#

just return

#

if you return at the start, the function's not gonna continue

#

P Y T H O N T E A C H E R

fervent shoal
#

like so?

cold sonnet
#

uh I think it would be better after the first if but before the return await

#

on the same level as the return await

fervent shoal
#

so what do i change

cold sonnet
#

or maybe even just after the for line

#

and after defining the function, check

if message.author.bot: return
``` ![yert](https://cdn.discordapp.com/emojis/832277526809149461.webp?size=128 "yert")
fervent shoal
cold sonnet
#

so switch the 2nd and 3rd if statement

#

just flip the order

fervent shoal
cold sonnet
#

yes

#

so this looks good

#

even tho

slate swan
#

I got command that replyโ€™s message.content but I want it to reply after the command and not include the command itself

cold sonnet
#

this checks the 2nd if statement many times

#

it's memorically dumb

fervent shoal
#

so im all set

cold sonnet
#

still works the same

cold sonnet
cold sonnet
#

because like

#

replies message.content

#

show us your code

pliant gulch
#
a = set(list_of_stuff)
b = set(message.content)

if b.intersection(a):
    ...
fervent shoal
#

it doesnt exist according to this code

#

do i have to import something

cold sonnet
#

then

slate swan
cold sonnet
#

await ctx.author.send(reason)

slate swan
#

Ok

cold sonnet
#

why is it named reason

outer parcel
#
@client.command()
async def shop(ctx):
  em=discord.Embed(title=f"Shop",description = f"the shop :/")
  for item in mainshop:
    name = item["name"]
    price = item["price"]
    description = item["description"]
    icon = item["icon"]
    em.add_field(name=f"{name} | {icon}", value = f"{price} Coins \n{description}")
  em.set_footer(icon_url = ctx.author.avatar_url, text = f"๐Ÿ’ธ | Requested by {ctx.author.name}")
  await ctx.reply(embed=em)
#

it keeps on saying invalid syntax

slate swan
slate swan
outer parcel
#

3rd

slate swan
#

Ok

cold sonnet
#

nah nothing's wrong there

outer parcel
#

ik

#

that is why im so confused

cold sonnet
#

but there's absolutely no need for f-strings

outer parcel
#

ok iguess ill leavit it

cold sonnet
#

lacking pep8

slate swan
#

I donโ€™t think it will Lmao

cold sonnet
#

why

slate swan
#

Ok Iโ€™ll try

cold sonnet
#

await ctx.author.send(reason if reason else "Send something or I'll kick your ass")

slate swan
#

It worked thx @cold sonnet

#

It worked but python thinks otherwise

torn sail
#

reason or โ€œsome random reason" also works instead of reason if reason else

cold sonnet
slate swan
#

Ok

cold sonnet
slate swan
#

Ok

cold sonnet
#

because it checks if reason's None

fervent shoal
#

none of these are working now

cold sonnet
#

you copied all of that cryingCat

fervent shoal
#

i just copy pasted and changed the things

#

it worked fine yesterday

cold sonnet
#

oh well

#

in the end of your on_message

#

put bot.process_commands(message)

fervent shoal
#

me?

cold sonnet
#

yes

#

to the very end of the function

#

bot.process_commands(message)

slate swan
fervent shoal
#

i am unable to see where

cold sonnet
#

put it there

#

or, second option

fervent shoal
#

@bot.command(name="ping")
async def ping(ctx: commands.Context):
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
@bot.command(name="ban")
@commands.has_permissions(manage_roles=True)
async def ban(ctx: Context, member: Member):
await member.ban()
embed1 = discord.Embed(title=f"{member}", description="insert description here")
await ctx.send(embed=embed1)
@bot.command(name="kick")
@commands.has_permissions(manage_roles=True)
async def kick(ctx: Context, member: Member):
await member.kick()
await ctx.send(f"{member} has been kicked")
@bot.command(name="mute")
@commands.has_permissions(manage_roles=True)
async def add_roles(ctx: Context, member: Member):
await member.add_roles(discord.Object(id=938658120715104306))
await ctx.send(f"{member} has been muted")
@bot.command(name="unmute")
@commands.has_permissions(manage_roles=True)
async def remove_roles(ctx: Context, member: Member):
await member.remove_roles(discord.Object(id=938658120715104306))
await ctx.send(f"{member} has been unmuted")

cold sonnet
#

no not in these

fervent shoal
#

why does the code look thiny never work

cold sonnet
#

of your on_message

fervent shoal
cold sonnet
#

jesus christ

#

no, undo that peepocry

slate swan
#

LOL

fervent shoal
#

idk how this helps the commands on top lemon_angrysad

cold sonnet
#

because

#

it will process the commands

#

if you do this right

fervent shoal
#

how do i do this right

cold sonnet
#

but there's a much better way without process_commands

#

and an easier one

#

replace @bot.event above the on_message line with @bot.listen()

slate swan
cold sonnet
#

so the decorator won't work the same

fervent shoal
#

ok

#

next step

cold sonnet
#

so now you have something like

@bot.listen()
async def on_message(message):
    ...
fervent shoal
cold sonnet
#

and it's done

#

wait

#

forgot the brackets

fervent shoal
#

waiting

cold sonnet
#

parantheses

fervent shoal
#

yes

cold sonnet
#

to @bot.listen()

fervent shoal
#

am i set

cold sonnet
#

yes