#discord-bots

1 messages · Page 482 of 1

slate swan
#

it's a library called dislash..it adds slash commands and buttons..do some research

lofty mulch
#

I renamed it from Setup to setup and not it suddenly works

#

Go figure

patent lark
lofty mulch
#

I hate not capitalizing words

slate swan
#
    @is_mod()
    @commands.command()
    async def say(self, ctx, channel: Union[discord.TextChannel, int, str], *, text):
        if isinstance(channel, discord.TextChannel):
            await channel.send(text)
        elif isinstance(channel, int):
            channel = self.bot.get_channel(channel)
            await channel.send(text)
        else:
            await ctx.send("**That's not a valid channel.**")

async def say(self, ctx, channel: Union[discord.TextChannel, id, str], *, text): TypeError: 'NoneType' object is not callable

#

what could be nonetype that I called?

#

wait oof

#

nah, still

spring flax
#

and get ratelimited, sure

slate swan
#

but ToS

slate swan
#

and how do you use the command , can show us the usage

slate swan
#

I gotta do some error handling I just realized

#

are you aware what selfbot is?

hasty iron
#

id is a function

slate swan
#

why would we help with that then?

hasty iron
#

!d id

unkempt canyonBOT
#
id

id(object)```
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same [`id()`](https://docs.python.org/3.10/library/functions.html#id "id") value.

**CPython implementation detail:** This is the address of the object in memory.

Raises an [auditing event](https://docs.python.org/3.10/library/sys.html#auditing) `builtins.id` with argument `id`.
slate swan
#

betterdiscord is not the only ToS breaking

slate swan
#

wtf

#

you want to tho

strong kettle
slate swan
#

do it manually if its just 15 people

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

i mean , we cant

hasty iron
#

whats the problem here

#

self bot?

slate swan
#

dpy

#

you cannot mass edit users

hasty iron
#

ok then what’s breaking tos

slate swan
#

too many API calls

hasty iron
#

what if you sleep between calls

patent lark
#

what here is breaking tos? i dont understand

slate swan
#

.

hasty iron
#

ok so some admin = him?

#

can you actually read?

#

whats the issue here

patent lark
#

since when is changing peoples nickname against ToS, if they wanna get ratelimited then go for it. stop making it a bigger deal than it is.

hasty iron
#

what the problem that you’re having

#

oh you want to edit everyone’s nickname

#

do you have anything yet?

#

ok

#

Guild.members is probably what you want it returns a list of guild members

#

then you can do Member.edit

patent lark
#

loop through guild.members and change the nickanmes

hasty iron
#

!d discord.Member.edit

unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
hasty iron
#

nick kwarg

patent lark
#

^

#
for member in ctx.guild.members:
  await member.edit(nick = "Ha Ha")
print("Done")```
drifting arrow
#

Anybody able to help me at all? it keeps saying inviter is None.

import discord, random, time, os, asyncio, sqlite3
from discord.ext import commands, tasks
from discord.ext.commands import Bot
import DiscordUtils


intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="$", intents=intents)
tracker = DiscordUtils.InviteTracker(bot)


@bot.event
async def on_member_join(member):
    inviter = await tracker.fetch_inviter(member)
    channel = bot.get_channel(794837147068792865)
    await channel.send("Someone has joined!")
    print(f'Inviter: {inviter}')
    print("--")
 bot.run(bottoken)  
hasty iron
#

discordutils is bad

#

you can probably make something better than it

drifting arrow
#

that doesnt help

hasty iron
#

then inviter is None cuz that fetch_inviter returned None

drifting arrow
patent lark
#

no

#

nick = whatever

drifting arrow
#

I'll just put this down and come back tomorrow with a fresh mind I guess

patent lark
#

👍

#
@bot.command()
async def nameall(ctx, *, whatever):
  for member in ctx.guild.members:
    await member.edit(nick = whatever)
print("Workz")```
#

that ^

abstract tundra
#

What should I use to code for a beginner would I use pycharm or visual studio?

patent lark
#

@commands.is_owner() would work

#

i dont know of a decorator for this, you could do something like

if ctx.author != ctx.guild.owner:
  return
else:
  #code here```
runic lagoon
#

I am confused

from dislash import slash_commands
from dislash.interactions import ActionRow, Button, ButtonStyle

    async def neko(self, ctx):
        """Neko Pictures!"""
        author = ctx.author
        result = await self.client.get_image("nekos")
        embed = discord.Embed(
            colour=author.colour,
            title=f"Neko!~"
        )
        embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
        embed.set_image(url=result.url)
        await ctx.reply(
            embed=embed,
            components = ActionRow(
                Button(style=ButtonStyle.link, label="Original", url=f"{result.url}")
                )
        )```

it shows ```     if len(components) > 5:
 TypeError: object of type 'ActionRow' has no len()```

any help?
slate swan
#

maybe try asking in the disnake help server

fleet axle
#

@slate swancan u help me in discord buttons I have a error

slate swan
#

also , where do you len(components)?
i dont see it in the code here

slate swan
abstract tundra
#

``# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')

client.run(TOKEN)``

#

is this good for now i just started it

slate swan
#

!d discord.ext.commands.Bot use this instead of discord.Client

unkempt canyonBOT
#

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

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

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

would be helpful while making commands

abstract tundra
#

i need to restart anyway i found that online

fleet axle
#

@slate swan Okay
I have created a calculator using discord buttons everything is done but when I click on a button it says this interaction is failed. how do I fix this?

abstract tundra
#

can anyone send me the begging i want prefix to be !

slate swan
fleet axle
#

@slate swan nope

slate swan
slate swan
fleet axle
#

Hmm can we talk tomorrow I am actually not with my pc rn
Sorry we can talk tomorrow if u can
Thankyou

slate swan
#

sure

#

its too late for me too , bye

fleet axle
#

Bye

#

Thanks for help

patent lark
#

yeah

#
for member in ctx.guild.members:
  if member.top_role.position < ctx.me.top_role.position:
    await member.edit(nick = nick)
  else:
    return```
#

@quartz beacon

#

yep.

#
@bot.command()
@commands.has_permissions(administrator=True)
async def nameall(ctx, *, whatever):
  for member in ctx.guild.members:
    if member.top_role.position < ctx.me.top_role.position:
      await member.edit(nick = whatever)
    else:
      return```
runic lagoon
#

DM me the inv

slate swan
slate swan
languid jungle
#

@patent lark posted this^

patent lark
#

but thank you :3

#

any errors?

patent lark
#

you're not indenting it correctly.

slate phoenix
#

you still have the indentation error you didnt change anything

patent lark
#

also, the bot should only be able to edit nicknames if their role is below the bots top_role anyways, so a check for it isnt needed, if its raising an exception you could just use a try-except block to catch it

slate phoenix
#

post your new code

patent lark
#

!d discord.Intents.members do you have this?

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

patent lark
#

ah events

#

nevermind.

lofty mulch
#

My error handler isn't working, all the errors are showing up on the terminal
Anyone could give a hand on his?

slate phoenix
patent lark
#

okay, so this should work

@bot.command()
async def nicknames(ctx, *, whatever):
  try:
    for member in ctx.guild.members:
      await member.edit(nick = whatever)
    print("Done")
  except Exception as e:
    print(e)```
abstract tundra
slate phoenix
#

yes

abstract tundra
#

ok

lofty mulch
#

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

patent lark
#

its trying to edit users nicknames above the bots role

#

do this instead

#
@bot.command()
async def nicknames(ctx, *, whatever):
  try:
    for member in ctx.guild.members:
      await member.edit(nick = whatever)
    print("Done")
  except Exception:
    pass```
slate phoenix
#

its on_command_errror

patent lark
#

^

lofty mulch
#

bruh

#

Lemme see

slate phoenix
#

also make sure to add an else block so that it logs errors that are not handled

patent lark
#
@commands.Cog.listener()
async def OnCommandError(self, ctx, error):```

no ^

```py
@commands.Cog.listener()
async def on_command_error(self, ctx, error):```

yes ^
abstract tundra
#

File "C:/Users/chris/PycharmProjects/PythonDisocrdBot#1/main.py", line 7 on_start print"Up and Running!" ^ SyntaxError: invalid syntax

#

what is wrong?

patent lark
#

it wouldnt work.

#

it cant, it would raise a Missing Permissions error

abstract tundra
# slate phoenix post full code

``import discord

from discord.ext import commands
bot = commands.Bot(command_prefix="!")

@bot.event
on_start print"Up and Running!``

lofty mulch
#

lacking the parenthesis

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
abstract tundra
slate phoenix
#

you have to put async def before on_start

patent lark
#

thats what it would do

lofty mulch
#

By the way, my own on_ready function also doesn't print an output for some reason, but the bot does function normally
Should I be worried or?

patent lark
#

we catch the exception and pass, so it doesnt crash our program, but it could be more efficient

patent lark
#

and whats the error

lofty mulch
slate phoenix
#

Dont capitalize the o

#

on_ready not On_ready

lofty mulch
#

ffs

#

I can't capitalize any of the functions?

patent lark
#

are you also using the event decorator?

hasty iron
#

pep8

slate phoenix
#

Not the ones that are built into discord.py, for commands though you can but i wouldnt

abstract tundra
#

I got another question

#

how do you remove defualt help command?

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

Active

Created

05-Jul-2001

Type

Process

patent lark
#

theres a better way

abstract tundra
#

``import discord

from discord.ext import commands
bot = commands.Bot(command_prefix="!")
bot.remove_command('help')

@bot.event
async def on_ready():
print("Up and running!")

@bot.command``

#

like this even though i didnt finish the command yet?

patent lark
#

commands.Bot() has a help_command kwarg, you can set this to None. bot = commands.Bot(...help_command=None...)

soft trout
#

Im making a level system, how would I sort the highest level people?

slate phoenix
abstract tundra
# patent lark <@!889219733877055538>

``import discord

from discord.ext import commands
bot = commands.Bot(help_command=None)

@bot.event
async def on_ready():
print("Up and running!")

@bot.command``

#

this?

patent lark
#

as far as im aware, it should be fine, we are simply looping through the members and changing the nickname, maybe you have done something wrong.

patent lark
#

command_prefix = "!"

abstract tundra
#

where do i put that?

patent lark
#

in the commands.Bot, just as you had it before?

abstract tundra
#

ok

patent lark
#

bot = commands.Bot(command_prefix = "!", help_command=None)

#

show me your code and any errors

unkempt canyonBOT
patent lark
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.pydis.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.

slate phoenix
#

iirc you cant do member.mention in the title you can do it in the embed description though

#

embed.description = member.mention

patent lark
#
@bot.command()
async def nicknames(ctx, *, whatever):
  print(1)
  try:
    print(2)
    for member in ctx.guild.members:
      print(3)
      await member.edit(nick = whatever)
      print(4)
    print("Done")
  except Exception:
    print(5)
    pass
    ```
do this and tell me which number it stops printing at
abstract tundra
patent lark
#

i edited it ^

patent lark
#

okay so its catching the exception

#

let me rewrite it

#
@bot.command()
async def nicknames(ctx, *, whatever):
  try:
    for member in ctx.guild.members:
      if member.top_role.position < ctx.me.top_role.position:
        print(1)
        await member.edit(nick = whatever)
    print("Done")
  except Exception:
    print(2)
    pass```
#

tell me what it prints

#

i am going to get food lol, ill help when im back, be back in like 3 minutes

#

nice

#

:)

soft trout
#

Im making a level system, how would I sort the highest level people?

full lily
#

if you're using a database, it probably has a sql keyword for sorting

#

I mean it definitely does

soft trout
#

or like i mean sort from highest to lowest

#

yk what i mean

full lily
#

yes

brazen seal
#

how i can do the bot send message in another line

slate swan
brazen seal
#

i don't understand

#

i have error

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

vague fable
#

Is it possible to build a rpg bot with discord.py? If possible, any hint of it?

gritty flame
#

why not

vague fable
#

I can't find any source on internet

#

So I was just wondering

dawn gale
#

i am not a coding expert but

vague fable
#

Like to make a game bot

dawn gale
#

do u mean text based game or like

vague fable
#

Ya

dawn gale
#

a card collecter game

vague fable
#

Both I would say

dawn gale
#

is it like the ones where u choose an option of what to do

vague fable
#

But ya more likely to be a card adventure game

dawn gale
#

is it like choose a b or c

vague fable
#

Ya

dawn gale
#

well aht in iteslf is easy.

#

like in python normaly its just ifs elifs and elses

#

witha bunch of inputs

#

so i would say try to read the document of discord.py

#

and try convert some stuff like the inputs

#

idk im not an expert

#

i am coding noob

vague fable
#

Sure

#

thanks a lot

dawn gale
#

if u want real helo

#

then u can ping the

#

team

vague fable
#

Name?

dawn gale
#

im finding it 1 sec

#

i think its helpers

vague fable
#

sure

#

thanks

dawn gale
#

np

#

if ur unsure

#

ask here again

#

coz im not a expert and i havent even read the document yet

vague fable
#

k

dawn gale
#

i would bet hat u know more pthon than me

#

just saying

vague fable
#

No I am not

#

I just learned how to code discord.py from yesterday

dawn gale
#

this is a example of one of my works

#

its a heads or tails game where u say 'cf h

#

and it does heads

#

thats how i take inputs for my basic games

vague fable
#

understandable

dawn gale
#

if ur really starting out

#

i wouldnt recommend jumping straight to a

#

rpg game

#

maybe practise some small projects. there are tutorials on youtube

#

ive currently made an 8 ball, heads or tails, ping, speak feature, and rock paper scissors

#

all very simple

vague fable
#

k

#

and one more question

#

which command should you use in order to make a reaction under a message sending by a bot

#

Long in short, how to let bot send reactions

dawn gale
#

the document should say that

vague fable
#

Sure

#

I will read it

dawn gale
#

its v important

vague fable
#

ik

dawn gale
#

anyway

#

good luck on ur bot

#

bye]

vague fable
#

ty ^^

lofty mulch
#

Could anyone point me a viable way to make the ctx.author change an embed without making it an absolute mess?

#

change an embed description*

dawn gale
#

feel free to ping me about the most basic basiccest stuff ever coz i am stupid

lofty mulch
#

I'll make sure to, thanks dude

#

@patent lark Are you there?

#

I don't think that my reload_cog command is actually reloading it, could you give me a hand?

steady flume
#

how to solve ?

river walrus
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

lofty mulch
#

I want to make an embed that can be changed according to the user's will

#

Thing is, I can't think of a way to piece it together without making the end product unreadable

slate swan
steady flume
slate swan
#

for 2.0 its avatar.url

steady flume
#

display_avatar ?

#

i just read

slate swan
#

german.avatar.url

lofty mulch
slate swan
#

member.icon_url

lofty mulch
#

It recognizes that I'm trying to reload the cog, but it doesn't complete the command

#

It's like it gets stuck halfway through it

slate swan
#

meh

burnt wharf
#

Are there any technologies/frameworks needed to be known before learning discord.py?

pliant gulch
#

You should learn OOP and async programming, then just the basics of python and you should be ready for discord.py

#

learn basic python before OOP and async programming* worded it wrong

floral crypt
#

Hello

sick prawn
#

heyya!

floral crypt
#

How can I know when does ctx.voice_client.play stop playing?

#

I mean

#

End

sick prawn
floral crypt
#

Not pause

#

Just ends

soft trout
#

AttributeError: 'int' object has no attribute 'sort'

@client.command()
async def leaderboard(ctx):
    for current_user in report['users']:
      lvl=current_user['level'].sort()
      print(lvl)

I dont understand whats wrong

river walrus
sick prawn
floral crypt
lofty mulch
formal rivet
#

Hello guys, I wanted to ask u for advice on the topic of programming discord bots in python.

I am coding the music bot in python using the default discordpy library, and the join command is essentially just coded as ctx.author.voice.channel.connect(). When typing !join, the bot joins immediately with a green circle and the command ctx.voice_client.is_playing returns true, although no sound is playing. I cannot leave this state with the commands ctx.voice_client.stop() or ctx.voice_client.pause(), unless I play a yt video and stop it with the aforementioned commands.

Did any of you also encounter this phenomenon? If this didn't happen to you while programming a discord bot, then that would also be greatly appreciated since that means that this state is not common and the mistake very likely lies within my setup code.

slate swan
#

now ytdl is against ToS

#

that's what I'm sure about

wild oak
#

Hey can anyone help me I'm trying to make my bot join a stage and stay there

#

But I don't know where to start

slate swan
#

can i ephemeral any message

floral crypt
#

Lul

wild oak
#

Please help

slate swan
#

hi, if i have a 2 argument command (ctx, arg) if i did not get the second arg, how do i send them that they have to enter a second arg too?

floral crypt
#

if arg is None:
ctx.send('whatever u wanna say')

slate swan
#

thanks 🙂

floral crypt
#

i think, not sure

reef shell
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

slate swan
#

and how can i make a continous task without blocking the whole bot with time.sleep arg,
like if i want to send a person a message every hour?

slate swan
#

😹

reef shell
#

lmao

#

search for it in the docs

slate swan
#

and it applies for every user?

#

like if i have an arg from 2 users at the same time

#

and i want to reply for them like if one sends true and other sends false, i want to reply the opposite

#

so it sends them the opposite every hour?

#

@reef shell

#

and if i stop the loop for someone will it continue for other ppl

reef shell
slate swan
#

I mean

#

If take the arguments eith bot.command

#

And then start tasks.loop

#

For two users

#

Will it send different values to them?

reef shell
#

explicitly say what are you trying to do

slate swan
#

Oky

#

So i am tracking a crypto

#

And every hour

#

It sends the price to the ppl who have their discord id and crypto name in database

#

But it can be different cryptos

#

For everyone

reef shell
#

yeah you can do that

final iron
#

Im using await guild.create_role(name="Moderator", permissions=, colour=rgb_color) to create a role. I want permissions= to equal a list/tuple/whatever that holds the roles permissions like this

administrator=False,
manage_messages=True,
manage_channels=True
#

I just don't know how to store them

reef shell
#

you don't need to kick start the loop after each command invokes

slate swan
#

Yea but the data is different for everyone

#

Like someone might track btc some might eth

#

So how do i do that?

reef shell
#

yeah that's another issue, you need to fetch data from database in the loop and do whatever you want

#

I'm not familiar with databases but that's the idea

patent lark
slate swan
#

So i need go modify to that?

patent lark
hasty iron
slate swan
#

And do you know maybe the answer for my other question?

patent lark
hasty iron
#

as the on_ready can be called multiple times

#

and calling start on a task more than once when it hasn’t finished leads to an error

slate swan
reef shell
hasty iron
#

you can take user input from tasks

#

just use wait_for

patent lark
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
slate swan
#

So? How would i do it?

final iron
#

How would I store permissions inside a variable like administrator=True

#

To use when creating a role

reef shell
slate swan
#

So I am updating my ping command to add an emoji but I am kinda braindead and it doesnt work@bot.command() async def ping(ctx): latency = round(bot.latency * 1000, 1) await ctx.send(f"**Pong! {latency}ms**") await bot.add_reaction(emoji)

hasty iron
patent lark
slate swan
#

No sorry usually it is message but I was testing

#

either way it doesnt work

hasty iron
#

okay

#

and what are we supposed to do then

#

you haven’t sent anything related to your issue

slate swan
slate swan
#

I am recoding my ping command to add an emoji. Here is the code:@bot.command() async def ping(ctx): latency = round(bot.latency * 1000, 1) await ctx.send(f"**Pong! {latency}ms**") await message.add_reaction(emoji) Error: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined

hasty iron
#

nameerrors are the basic of bascis

slate swan
#

oh and here is my variable

hasty iron
#

if you can’t solve them yourself you should learn python

slate swan
#

emoji = "892256570389667870"

patent lark
#

message is referenced one time, whats the value to this message you're trying to access?

slate swan
patent lark
#

yes

slate swan
#

@hasty iron
so basically my question was
i am receiving different hashes from people
and i put the hashes to an api
and then the api returns a number
but the hash can be different for everyone
so i want to make a loop
that starts for a person that is starting it
and send them the api returned value every hour
could u help?

patent lark
#

so then, you could access this message variable and use the add_reaction function

slate swan
#

My bad

#

lol

patent lark
slate swan
#

I am still getting the unknown emoji with ```emoji = ":ping_pong:id here"

@bot.command()
async def ping(ctx):
latency = round(bot.latency * 1000, 1)
message = await ctx.send(f"Pong! {latency}ms")
await message.add_reaction(emoji)```

#

I put "id here" because its getting deleted

reef shell
#

you either need to use a unicode emoji or you have to use bot.get_emoji to get and then use it to add reaction to the message

#

and read the docs first

slate swan
#

ok one moment

patent lark
#

if you're using a default emoji, you can simply paste the emoji itself, in the code and it would work

#

?

normal oxide
#

Don't mind me

slate swan
#

hell yeah!!

patent lark
final iron
#

How would I make a parameter in a command optional?

slate swan
#

Thank you @patent lark I never really tried to add a reaction with a bot you were a big help

hasty iron
patent lark
hasty iron
#

it is the right direction

#

learning python should come first

slate swan
#

Not really it might be harder but teaching myself in my opinion is better than not

#

anyways imma go thanks again @patent lark

patent lark
lyric moat
#

error py @commands.command() async def calculate(ctx, operation, *nums): if operation not in ['+', '-', '*', '/'] await ctx.send('Please type a valid operation type.') var = f' {operation} '.join(nums) await ctx.send(f'{var} = {eval(var)}')

patent lark
#

forgot a :

hasty iron
#

missing :

hasty iron
#

basic python issues

lyric moat
#

i did put :

#

and i get

hasty iron
#

clearly not

lyric moat
#

nvm i fixed it

patent lark
hasty iron
#

ok so what should i have said

#

basically make a longer sentence

#

and it’s "nicer and friendly"

lofty mulch
#

Blanket

lyric moat
#

this works but it gives no error and would not reply

  @commands.command()
  async def calculate(ctx, operation, *nums):
      if operation not in ['+', '-', '*', '/']:
        await ctx.send('Please type a valid operation type.')
        var = f' {operation} '.join(nums)
        await ctx.send(f'{var} = {eval(var)}')```
hasty iron
#

there is no point writing a whole paragraph on somebody’s lack of knowledge

lofty mulch
#

I seriously don't know what to do anymore

#

Could you give me a hand?

hasty iron
patent lark
lofty mulch
#

It freezes halfway through it

lyric moat
lofty mulch
#

And just won't do anything after that, even when I try to call it back

lofty mulch
#

k

dapper cobalt
lofty mulch
#
@commands.command(name='Recarregar', aliases=['r','re', 'reiniciar', 'reload', 'rel'])
    async def reload (self, ctx):
        if ctx.author.id == 852643106482683934:
            try:
                await ctx.message.delete()
            except:
                pass

            message = await ctx.send("Recarregando as extensões.", delete_after=10)
            for filename in os.listdir():
                self.bot.reload_extension()
            for filename in os.listdir():
                await ctx.send(f'{filename[:-3]} foi carregado!', delete_after=10)
                await ctx.send('Todas as extensões foram carregadas!', delete_after=10)
        else:
            await ctx.send('Quem é você? Mete o pé!')

hasty iron
patent lark
lofty mulch
#

bruh

#

extension argument?

pliant gulch
#

You need to pass the name of the extension

#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
lofty mulch
#

Well, it's a general reloader

pliant gulch
#

Your iterating os.listdir() just pass the names from there into reload

lofty mulch
#

Can I just add all of my cogs to a list and add it as an argument?

reef shell
#

not as an arg

pliant gulch
#

No because it takes a single name

#

Not a list of names

reef shell
#

you can iterate the list

lofty mulch
#

Well, what's a viable option to do it?

hasty iron
lyric moat
hasty iron
#

they lack knowledge and that’s it

#

and they know they do

lofty mulch
pliant gulch
#

Just like how you load the extensions in the first place

hasty iron
pliant gulch
#

But if you have a list of valid cog alr you can iterate that instead of os.listdir()

patent lark
lyric moat
lofty mulch
hasty iron
lofty mulch
#

So it's already on the cog files

patent lark
dapper cobalt
#

I don't think blanket gave an attitude. It's just common sense, they're asking for help regarding basics of Python in an advanced section?

reef shell
final iron
hasty iron
reef shell
hasty iron
#

its a topic they should touch on when they get some knowledge first

lofty mulch
lyric moat
lofty mulch
#

I tried Discord.py before properly learning Python and it took me like 6 hours before I could get my bot online

slate swan
#

what

lofty mulch
#

I was struggling with getenv

dapper cobalt
# lyric moat what should i put?
  @commands.command()
  async def calculate(ctx, operation, *nums):
    if operation not in ['+', '-', '*', '/']:
      return await ctx.send('Please type a valid operation type.')
    var = f' {operation} '.join(nums)
    await ctx.send(f'{var} = {eval(var)}')
#

"un-tab".

pliant gulch
#

I wouldn't say discord bots are a advance topic, rather the topics it depends on are such as OOP and async programming

#

I don't even fully understand async programming myself yet

lyric moat
#

does not even reply

hasty iron
#

you shouldn’t use eval for stuff like that

#

especially with user input

wispy spade
#

You generally should avoid eval (and it's friend exec) at all costs.

reef shell
#

what will happen when someone uses '/' lmao

lofty mulch
wispy spade
lofty mulch
#

that actually sounds fun, I'll add it

#

Gives me dem jollies

dapper cobalt
lofty mulch
#

Imagine creating a bot that can literally delete you

patent lark
wispy spade
hasty iron
#

i get your point too

pliant gulch
wispy spade
#

If you want to do calculators, maybe take a look at the MathJS API or at some math interpreter like numexpr.

patent lark
lofty mulch
#

This actually sounds really fun

dapper cobalt
lofty mulch
#

Creating a bot that can literally delete your PC

pliant gulch
lofty mulch
#

and leaving it at the hands of people that you barely know

pliant gulch
#

Well, if you use windows I don't think it would allow you to do that either way

hasty iron
#

if you run the bot using admin perms it will iirc

lofty mulch
pliant gulch
#

windows has rm -rf?

#

and $HOME?

hasty iron
#

no

hasty iron
#

but you can delete stuff

lost lagoon
#

Does anyone know how i could break this up? kind of text heavy

lofty mulch
#

It's like playing russian roulette, but with a discord bot

pliant gulch
#

more like Russian roulette but you always lose

dapper cobalt
hasty iron
#

no not really

wispy spade
lofty mulch
wispy spade
#

Although, yeah, use an embed for those. They are cool 🙂

lost lagoon
#

K

patent lark
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

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

thanls

#

thanks

lofty mulch
#

living on the constant fear of randomly being deleted

hollow agate
#
@client.event
async def on_message_delete(message):
    if message.guild:
        if message.author.bot:
            return
        time = datetime.now(tz=pytz.timezone('America/Tijuana'))
        formatted = time.strftime("%I:%M %p")
        msgtime = (time - message.created_at).total_seconds()
        logchannel = client.get_channel(872911089258598421)
        am = discord.AllowedMentions(
            users=False,
            roles=False,
            everyone=False,
            replied_user=False,
        )
        await logchannel.send(f'[`{formatted}`] Message by {message.author} `({message.author.id})` in {message.channel.mention} has been removed. ({round(msgtime, 2)} seconds after being sent) \n**Content**: {message.content}', allowed_mentions=am)
    else:
        return``` So let's say this message exceeds the 2,000 character limit, is it possible to put the contents of the message into a .txt file if it does? If so, how can I start it?
hasty iron
lofty mulch
#

Nope, I'm a real person last time I checked

patent lark
#

interesting.

lofty mulch
hasty iron
#

although idk if they have limits for lines

hollow agate
dapper cobalt
lofty mulch
#

huh

#

didn't know that

dapper cobalt
#

I knew that recently.

hasty iron
#

discord does that in the client

hasty iron
#

not for bots

pliant gulch
lofty mulch
#

discord.ext.commands.errors.ExtensionAlreadyLoaded: Extension 'Cogs.DevelopmentCmds' is already loaded.

Exception for already loaded files?

hasty iron
lofty mulch
#

Wait

#

I'm actually loading it up twice

hollow agate
#

Oh bet! Thank you :)

lofty mulch
#

What am I even doing

patent lark
#

🤨

lofty mulch
#

I think it worked, lemme try it

#

and not it won't answer me, epic

lyric moat
#

first message o

dapper cobalt
unkempt canyonBOT
dapper cobalt
#

Damnit.

patent lark
final iron
#

Can I get a little clarification on remove_roles. One of the parameters is *roles which im guessing means remove all the roles but how would I implement it?

lofty mulch
hasty iron
#

n being positive above 0

final iron
#

I really have no idea what that means

hasty iron
#

basically like Member.add_roles(first_role, second_role, third_role, …, n_role)

dapper cobalt
#

Top.gg would've reviewed 2 bots and you wouldn't have gotten rich still.

patent lark
#

rip..

final iron
#

Is it possible to store permissions inside a variable like this

permissions = [
  administrator=True
  manage_messages=True
  ]
#

And use it in a context of creating a role

slate swan
#

Can't you just use the permissions interger

final iron
#

Wdym

slate swan
#

Like 8 is administrator right?

lofty mulch
#

Can't you just go

final iron
#

Im not looking for administrator specifically

#

Its just an example

lofty mulch
#
@commands.command(pass_context=True
@has_permission(administrator=True)
#

Can't you just do this

final iron
#

I'm creating a role

lofty mulch
#

oh

#

idk then

pliant gulch
#

By doing this as well you can pass that directly to the permissions kwarg of the role

final iron
#

Can I get an example or some documentation

pliant gulch
#

!d discord.Permissions

unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.update "discord.Permissions.update").
final iron
#

Can I get an example on how to use this

pliant gulch
#

Notice the **kwargs in the documentation

lofty mulch
#

May Jesus bless the guy that thought about replacing words with Ctrl Alt Enter on Vscode

final iron
#

I still don't understand it

#

It would be easier if I could just get an example

pliant gulch
#

Weren't you saying this stuff wasn't advanced earlier, and now your asking me how to create an instance???

final iron
#

When I said it wasn't advanced I didn't mean that I had really good knowledge

lofty mulch
#

lmao

final iron
#

Its literally just not advanced

pliant gulch
#

then creating an instance should be pretty easy no?

slate swan
#

lol

final iron
#

I had no knowledge of this when I said that

lofty mulch
#

By the way, is this supposed to be Github?

final iron
#

So am I doing this right?


        permissions = discord.Permissions(view_channels=True,
                                          manage_channels=False,
                                          manage_roles=True,
                                          manage_emojis_and_stickers=True
                                          )
#

And if I am doing it right would the permission default to Falseif I don't define it or will I have to define all the permissions?

lost lagoon
#

Im having a problem with the embed

jade jolt
#

thats old code

patent lark
#

it would be await ctx.send(embed = embed)

slate swan
#

await ctx.send()

lost lagoon
#

k

jade jolt
#

how did he find client.say?!

lost lagoon
jade jolt
#

my god

patent lark
#

dont ; copy ; code

jade jolt
#

dont use youtube tutorials

slate swan
#

thats old

dawn gale
#

Lichrally all of my bot is YouTube tutorials

jade jolt
#

literally just showed why

dawn gale
#

Like 5 whole commands

lost lagoon
#

does anyone know why the images wont load?

slate swan
#

bad internet?

dawn gale
#

Is it coz old code

lost lagoon
#

do you know the new code for loading images?

patent lark
jade jolt
#

thats so old

lost lagoon
#

im sorry

patent lark
#

old old

jade jolt
#

very

final iron
lost lagoon
#

does anyone know the new way of loading images

lusty swallow
#

yeah it just there for compatability reason. move on to client.send

lost lagoon
final iron
zinc geyser
#

This:

ov={
    ctx.guild.default_role: discord.PermissionOverwrite(None),
    ctx.message.author: discord.Permission(49524544)}
category = await ctx.guild.create_category(name, overwrites=ov)

Gives me this err:

-TypeError: __init__() takes 1 positional argument but 2 were given
zinc geyser
lost lagoon
#

?

unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

zinc geyser
#

did i spell it wrong?

lusty swallow
#

not sure what discord.Permission() is

patent lark
#

example

@bot.command()
async def test(ctx):
  embed = discord.Embed(title = "Hello", description = "Hello", colour = discord.Colour.red(), timestamp = ctx.message.created_at)
  embed.add_field(name = "Hello", value = "Hello")
  embed.set_footer(text = "Hello", icon_url = ctx.author.avatar_url)
  await ctx.send(embed = embed)```
@lost lagoon
zinc geyser
patent lark
#

an image would be like

embed.set_image(url = "link")
embed.set_thumbnail(url = "link")```
lost lagoon
#

yeah that exactly what i di

patent lark
#

or you could use ctx.author.avatar_url if you're trying to get a users pfp

final iron
#

TypeError: 'view_channels' is not a valid permission name. No idea why this is happening because it obviously is a valid permission

        permissions = discord.Permissions(view_channels=True,
                                          manage_channels=False,
                                          manage_roles=True,
                                          manage_emojis_and_stickers=True
                                          )
lusty swallow
patent lark
lost lagoon
#

is there something wrong with the links?

patent lark
#

let me see your code

lost lagoon
final iron
#

Like view_channel and manage_roles

patent lark
#

maybe your internet cant load the image lol.

lusty swallow
#

why not

final iron
lost lagoon
final iron
#

Its weird

#

Well I guess it will be a lot of trial and error

#

Actually the proper syntax is in the documentation

pliant gulch
#

You know, if you read the docs it gives you every valid permission name

patent lark
pliant gulch
lost lagoon
#

@pliant gulch

pliant gulch
#

The direct link to the image

lost lagoon
#

so like a discord linked image

#

or?

pliant gulch
#

no just the direct link to the image rather then a google url

lost lagoon
#

k

patent lark
burnt wharf
#

And I know how to express it in code. Besides them, is there anything else?

pliant gulch
#

Have you checked out the docs for discord.py? Are you able to read them?

#

After being able to read the docs that's pretty much it

#

There is also resources such as vco's tutorial

lost lagoon
#

cause im not sure how to get the direct link for the image im looking for

burnt wharf
lost lagoon
patent lark
#

you find the image

#

right click

#

copy image link

lost lagoon
#

thats giving me link address

#

nvm now its working but its like this

round quarry
#

What is the manage roles permission called ?, when should I put has.permissions ()

hollow agate
patent lark
#

@commands.has_permissions(manage_roles=True)

round quarry
#

thanks to both :P

patent lark
#

👍

lost lagoon
#

@patent lark @pliant gulch Thanks for all the help!

patent lark
#

no problem

lyric moat
#

how i make the bot owner only can use a command i tried this and it made everyone can shut down the bot

@client.command()
@commands.is_owner()
async def shutdown(ctx):
    await ctx.bot.logout()```
patent lark
#

i can assure you that @commands.is_owner() only allows the bot owner to use the command.

lyric moat
#

lemme try on my atl

hollow agate
#
@client.command()
async def removelogging(ctx, msg = None):
    if msg == None:
        await ctx.channel.send('You must actually mention a channel ID!')
    else:
        with open("data.json") as f:
            data = json.load(f)
        
        if msg 
    
        data["no-log-channels"].append(msg)

        with open ("data.json", "w") as f:
            json.dump(data, f)
    
        await ctx.channel.send('Done.')``` How can I check if the msg (channel id) is already in the data?
round quarry
#

I can make the bot say something like: There is no such role, you will have to create the role.

steep topaz
#

!voiceverify

patent lark
#

<#channel_id_here>

#

@slate swan

#

👍

#

i edited it ^

final iron
#

Im getting Forbidden: 403 Forbidden (error code: 50013): Missing Permissions when trying to edit a users nickname. My bot has max perms and in the roles list its the highest possible.

#

I used the setting where you can look at the server like people with the role can and I have permission to edit a users nickname

#

I'm stumped

solemn ocean
final iron
#

You don't need the star btw

solemn ocean
#

ok ill removei t

#

then

final iron
#

Whats the error?

solemn ocean
final iron
#

Oh the bot.command() is on the wrong indentation level

#

It needs to be on the same level as async def

solemn ocean
#

ok

#

@final iron

patent lark
#

bro

#

it needs to be under it.

#

the command decorator and function definition do not go on the same line

solemn ocean
#

PH

#

same line no neck mb

#

yeah i got it theres still an error

#

diff line tho

final iron
#

Send the code

solemn ocean
patent lark
#
@bot.command()
async def hey(ctx):
  await ctx.send("Hi")```
#

look at how thats indented

final iron
solemn ocean
#

alr done that

#

im a newgen in python lol

final iron
#

I'm guessing you're following a guide right

#

Because if you don't know proper indentation I doubt you can write something that actually works

solemn ocean
#

yea

#

😔

final iron
#

Make sure its not an old guide

solemn ocean
#

alr

final iron
#

Im getting Forbidden: 403 Forbidden (error code: 50013): Missing Permissions when trying to change a users nickname

#

The bots role has perms to do it

#

Maybe its an intents thing but I have them all enabled

slate swan
#

await user.edit(nick="testy")

dapper cobalt
slate swan
#

^^

dapper cobalt
#

!d asyncio.sleep

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3.10/whatsnew/3.10.html#whatsnew310-removed) for more information.

Example of coroutine displaying the current date every second for 5 seconds:
final iron
#

I used the setting to view the server as a person with the role could and its allowed to change nicknames

final elk
#

process

slate swan
#

how do i get the mobile status thingy

#

for my activity

patent lark
#

!d discord.Member.is_on_mobile

unkempt canyonBOT
#

is_on_mobile()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): A helper function that determines if a member is active on a mobile device.
patent lark
#

@slate swan

slate swan
#

so ActivityType.is_on_mobile

patent lark
#

no, that wouldnt work

#

i dont think you can make a bot appear as on mobile

slate swan
#

yes you can

patent lark
#

this is for the member object

#

you can?

#

!d discord.ActivityType

unkempt canyonBOT
#

class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Activity "discord.Activity"). This is used to check how to interpret the activity itself.
slate swan
patent lark
pliant gulch
#

No its a bug on discord

patent lark
#

@slate swan

pliant gulch
#

Bug as in not intended, and cannot be done with discord.py*

slate swan
#

so many bots have it tho..

#

okay

patent lark
slate swan
#

how do i change the bots status

#

like do not disturb or

final iron
#

Snow any idea why it says im missing permissions?

patent lark
slate swan
#
    while True:
        await bot.change_presence(status=discord.Status.idle,
            activity=discord.Activity(type=discord.ActivityType.competing,
                                      name=f",help | {len(bot.users)} Users"))
        await asyncio.sleep(3)
        await bot.change_presence(status=discord.Status.idle,
          activity=discord.Activity(type=discord.ActivityType.competing,name=f",support | {len(bot.guilds)} Guilds"))
        await asyncio.sleep(3)
``` now its just oline
#

online

#

How can I convert seconds into minutes, hours, day, week in cooldown

final iron
lyric moat
#

How i make my bot do ship command like this?

#

like mostly the image

#
@client.command()
async def Ship(ctx, user_1 : discord.Member, user_2 : discord.Member):
    await ctx.send(f"{user_1.mention} and {user_2.mention} seem nice together")
patent lark
#

i would use an embed

lyric moat
#

ima use a embed but how i make the image of user one and two?

visual island
#

use PIL library

#

!pypi PIL

unkempt canyonBOT
lyric moat
#

But can i add like a random number to it?

rugged tinsel
#

hey is it possible to make your prefix case insensitive? kinda new to coding

valid perch
#

!d discord.Member.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

ok!

valid perch
#

Code?

rugged tinsel
#

do I just copy and paste that or do I have to type it in?

valid perch
#

Looks fine?

fleet oracle
#

How can I divide all the files into different folders?

valid perch
#

Just put them in different folders?

supple thorn
#

nukeRed

fleet oracle
bitter perch
#

A cog per command

fleet oracle
#

you say i have to do a cogs by command?

visual island
slate swan
#
for member in ctx.guild.members:
            if role not in member.roles:
                await member.add_roles(role)
``` how can i get how many members that is
visual island
#

case_insensitive doesn't make your prefix case insensitive (only command names to be insensitive) so, sure

slate swan
#

oh it should do like member += 1

visual island
slate swan
visual island
#

make another variable

slate swan
#

okay

#

so just user += 1

visual island
#

you cant? let me try

#

you can

#

you put your case_insensitive in the list

#

client = commands.Bot(command_prefix = ["HC ", "*"], case_insensitive=True)

#

it's fine CH_ThumbsUpSmile

slate swan
#
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount : int):
    await ctx.channel.purge(limit=amount)
    await ctx.send(f'Melding Clearing Ferdig!')```
#

it doesnt clear commands

#

cuz i have a class and i have no fucking clue how to work with classes

#
from discord.ext import commands

bot = discord.Client()

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

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

@bot.command()
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount : int):
    await ctx.channel.purge(limit=amount)
    await ctx.send(f'Melding Clearing Ferdig!')


class MyBot(discord.Client):

    async def on_ready(self):


        print('Logged on as', self.user)

    async def on_message(self, message):
        word_list = ['Hore', 'faen', 'Faen', 'hore', 'fitte', 'Fitte', 'fuck', 'Fuck']

        # don't respond to ourselves
        if message.author == self.user:
            return

        messageContent = message.content
        if len(messageContent) > 0:
            for word in word_list:
                if word in messageContent:
                    await message.delete()
                    word_list = ['Hore', 'faen', 'Faen', 'hore', 'Fitte', 'fitte', 'fuck', 'Fuck']
            
        messageattachments = message.attachments
        if len(messageattachments) > 0:
            for attachment in messageattachments:
                if attachment.filename.endswith(".dll"):
                    await message.delete()
                    await message.channel.send("Det er ikke lov med .dll filer.")
                if attachment.filename.endswith('.exe'):
                    await message.delete()
                    await message.channel.send("Det er ikke lov meg .exe filer.")
                else:
                    break
                
bot = MyBot()              
bot.run('my discord bot token')```
#

the whole thing

boreal ravine
#

just use commands.Bot and not discord.Client

slate swan
#

why do you have both client and commands.Bot in the code?

slate swan
#

Traceback (most recent call last):
File "c:\Users\walle\Desktop\Discord bot\Øbot.py", line 4, in <module>
bot = commands.Bot()
TypeError: init() missing 1 required positional argument: 'command_prefix'

#

i switched bot = discord.Client()to bot = commands.Bot()

valid perch
#

Give it an argument called command_prefix

#

Which is your commands prefix

drifting arrow
#

Guys

#

I require assistance

#
import discord, random, time, os, asyncio, sqlite3
from discord.ext import commands, tasks
from discord.ext.commands import Bot
import DiscordUtils

@bot.event
async def on_member_join(member):
    inviter = await tracker.fetch_inviter(member)
    channel = bot.get_channel(794837147068792865)
    await channel.send("Someone has joined!")
    print(f'Inviter: {inviter}')
    print("--")
``` this doesnt work for some reason help D:
slate swan
#

u got bot.run('token') right?

drifting arrow
#

Yes

#

The part I want to focus on is inviter = await tracker.fetch_inviter(member)

slate swan
#

any errors?

drifting arrow
#

inviter = await tracker.fetch_inviter(member) doesnt give me any values ;-;

slate swan
#

hm @valid perch

#

here u go i got something for u

#

help this guy ❤️

sinful marsh
#

Is there a built in command with discord.py that goes by the name of configure?

vocal plover
#

no

sinful marsh
#

And if so is it useful/important

#

what the hell than lol

#

nevermind

lyric moat
#
    await ctx.send(f"{user_1.mention} and {user_2.mention} seem nice together")```
how can i turn this into an embed ?
slate swan
#

I need bot hosting

drifting arrow
#

@lyric moat

embed = discord.Embed()
embed.add_field(name="My Field", value=f"{user_1.mention} and {user_2.mention} seem nice together", inline="False")
await ctx.send(embed=embed)
#

Now fix my issue ;-;

lyric moat
#

{user_1.mention} and {user_2.mention} are in 85% love

#

how i do that?

twilit adder
slate swan
#

I need bot hosting please help me

valid perch
#

Theres heaps you can get online, such as vultr, digital ocean etc

#

Once you have a vps you can follow some tutorials for running your bot 24/7

stiff ermine
#

how can i get the channel id from a message object of on_message(message) function?

pliant gulch
#

discord.Message instances have a channel attribute which will be the discord.TextChannel which the message was sent in, which also has an id property

stiff ermine
#

thnx

vital condor
#

Hey guys i was wondering if i could make a discord bot from python is that possible?

#

I am new to python

valid perch
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

valid perch
#

@vital condor

vital condor
#

thankyou

#

This community is very helpfull thanks python

lofty heron
#

hi i'm not sure how to specify the amount of seconds left in my cooldown, i've gotten the on command error event setup but idk how to make it say how much left you have to wait to run the command again

#command error handlers
@client.event
async def on_command_error(ctx, error, exc):
    if isinstance(error, commands.CommandNotFound):
        embed = discord.Embed(
            title="Error!",
            description="Command not found \n run `da!help` to see all the commands",
            colour=ctx.author.colour
        )
        await ctx.send(embed=embed)
    elif isinstance(error, CommandOnCooldown):
      await ctx.send('That command is on cooldown.')
drifting arrow
#

How do I get the guild id without using ctx?

lofty heron
#

uh i don't think you can get it without ctx

drifting arrow
#

pretty sure you can

stoic galleon
#

!eval
@commands.command()
async def botinfo(self, ctx):
embed = discord.Embed(title= 'Jackal',url='https://discord.com/api/oauth2/authorize?client_id=889183519501328384&permissions=8&scope=bot',icon_url= 'https://images-ext-2.discordapp.net/external/ZzS0qALknuHHH2Jxb013cnQPqTLgYxh3YFDZ0gRZG7c/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/889183519501328384/b4b59d22618e50d0c4c620f61a8ff16c.png')
embed.add_field(name='Stats', value= f'Guilds {len(self.client.guilds)}\nUsers {len(self.client.users)}\nCommands {len(self.client.commands)}',inline=False)
embed.add_field(name='Infomation', value= f'Version 1.0.0\nDiscordPY 1.7.3\nPython 3.8.2',inline=False)
await ctx.send(embed=embed)

unkempt canyonBOT
#

@stoic galleon :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     async def botinfo(self, ctx):
003 | IndentationError: unexpected indent
drifting arrow
#

your indents bro

stoic galleon
#

mhm

#

o nvm

boreal ravine
#

@stoic galleon use jishaku to debug/run code

boreal ravine
#

I think I'm not sure though

stoic galleon
drifting arrow
lofty heron
#

um

drifting arrow
# stoic galleon !eval @commands.command() async def botinfo(self, ctx): embed...

you were missing a few '

@commands.command()
async def botinfo(self, ctx):
    embed = discord.Embed(title= 'Jackal',url='https://discord.com/api/oauth2/authorize?client_id=889183519501328384&permissions=8&scope=bot%27',icon_url= 'https://images-ext-2.discordapp.net/external/ZzS0qALknuHHH2Jxb013cnQPqTLgYxh3YFDZ0gRZG7c/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/889183519501328384/b4b59d22618e50d0c4c620f61a8ff16c.png%27')
    embed.add_field(name='Stats', value= f'Guilds {len(self.client.guilds)}\nUsers {len(self.client.users)}\nCommands {len(self.client.commands)}',inline=False)
    embed.add_field(name='Infomation', value= f'Version 1.0.0\nDiscordPY 1.7.3\nPython 3.8.2',inline=False)
    await ctx.send(embed=embed)
boreal ravine
lofty heron
#

idk if you can without ctx kek

#
@commands.command()
async def guildid(self, ctx):
    await ctx.send(f'{ctx.message.guild.id}')
#

um idk how to do without ctx

boreal ravine
lofty heron
#

huh interesting

drifting arrow
#

I know that works..

#

I want to be able to do it without needing an input of any sort

boreal ravine
#

an input?

drifting arrow
#

I dont want to have to rely on events like on_message and a command

#

i want to be able to run some setup code

boreal ravine
#

I dont understand lel

drifting arrow
#

Before my bot 'goes online' I need to setup some stuff, like the database etc. and part of my logging is by guild_id.

#

and i need to grab data by server

stoic galleon
#

wha do i need to fix

#

im confused

drifting arrow
#

what is the error*

stoic galleon
#

doesnt say a error

#

jus never sends

drifting arrow
#

You are missing a lot of quote marks

stoic galleon
#

where

drifting arrow
#

Can you send all the code?

#

@stoic galleon

stoic galleon
#
 @commands.command()
    async def botinfo(self, ctx):
        embed = discord.Embed(title= '**Jackal**', url= 'https://discord.com/api/oauth2/authorize?client_id=889183519501328384&permissions=8&scope=bot', icon_url= 'https://images-ext-2.discordapp.net/external/ZzS0qALknuHHH2Jxb013cnQPqTLgYxh3YFDZ0gRZG7c/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/889183519501328384/b4b59d22618e50d0c4c620f61a8ff16c.png')
        embed.add_field(name='**Stats**', value= f'**Guilds** {len(self.client.guilds)}\n**Users** {len(self.client.users)}\n**Commands** {len(self.client.commands)}',inline=False)
        embed.add_field(name='**Infomation**', value= f'**Version** 1.0.0\n**DiscordPY** 1.7.3\n**Python** 3.8.2',inline=False)
        await ctx.send(embed=embed)
#

idk why is looks like tha

#

well the idents look like tha

drifting arrow
#

lol

#

dw about the indents on discord.

stoic galleon
#

mhm whats the error tho

drifting arrow
slate swan
#

This is cross server chat I had seen what may be the mechanism used

drifting arrow
slate swan
drifting arrow
# stoic galleon mhm whats the error tho
    @commands.command()
    async def botinfo(self, ctx):
        embed = discord.Embed(title= '**Jackal**', url= 'https://discord.com/api/oauth2/authorize?client_id=889183519501328384&permissions=8&scope=bot')
        embed.set_thumbnail(url="https://images-ext-2.discordapp.net/external/ZzS0qALknuHHH2Jxb013cnQPqTLgYxh3YFDZ0gRZG7c/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/889183519501328384/b4b59d22618e50d0c4c620f61a8ff16c.png")
        embed.add_field(name='**Stats**', value= f'**Guilds** {len(self.client.guilds)}\n**Users** {len(self.client.users)}\n**Commands** {len(self.client.commands)}',inline=False)
        embed.add_field(name='**Infomation**', value= f'**Version** 1.0.0\n**DiscordPY** 1.7.3\n**Python** 3.8.2',inline=False)
        await ctx.send(embed=embed)
#

Was this what you wanted @stoic galleon ?

lyric moat
#

why it keeps saying this when i add invites.py in cog

stark hearth
#

praw for importing reddit post was great for me, but i want to move to asyncpraw. i having a hard time with that.

from discord.ext import commands
import discord
import asyncpraw

    @commands.command()
    async def meme(self, ctx):
        
        reddit = asyncpraw.Reddit(
            client_id="stuff",
            client_secret="stuff",
            user_agent="stuff",
            )
        
        subreddit = reddit.subreddit("dankmemes")
        all_subs = []

        for submission in subreddit.top(limit = 100):
            all_subs.append(submission)  

        random_sub = random.choice(all_subs)

        name = random_sub.title

        embed = discord.Embed(title = name)

        embed.set_image(url = random_sub.url)
        await ctx.send(embed = embed)

error
RuntimeWarning: coroutine 'SubredditHelper.__call__' was never awaited self._context.run(self._callback, *self._args) RuntimeWarning: Enable tracemalloc to get the object allocation traceback

drifting arrow
lyric moat
#
import discord
import DiscordUtils
from discord.ext import commands

# Requires: pip install DiscordUtils


class Invites(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.tracker = DiscordUtils.InviteTracker(bot)

    @commands.Cog.listener()
    async def on_ready(self):
        await self.tracker.cache_invites()

    @commands.Cog.listener()
    async def on_invite_create(self, invite):
        await self.tracker.update_invite_cache(invite)

    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        await self.tracker.update_guild_cache(guild)

    @commands.Cog.listener()
    async def on_invite_delete(self, invite):
        await self.tracker.remove_invite_cache(invite)

    @commands.Cog.listener()
    async def on_guild_remove(self, guild):
        await self.tracker.remove_guild_cache(guild)

    @commands.Cog.listener()
    async def on_member_join(self, member):
        inviter = await self.tracker.fetch_inviter(member)  # inviter is the member who invited
        data = await self.bot.invites.find(inviter.id)
        if data is None:
            data = {"_id": inviter.id, "count": 0, "userInvited": []}

        data["count"] += 1
        data["usersInvited"].append(member.id)
        await self.bot.invites.upsert(data)

        channel = discord.utils.get(member.guild.text_channels, name="recording")
        embed = discord.Embed(
            title=f"Welcome {member.display_name}",
            description=f"Invited by: {inviter.mention}\nInvites: {data['count']}",
            timestamp=member.joined_at
        )
        embed.set_thumbnail(url=member.avatar_url)
        embed.set_footer(text=member.guild.name, icon_url=member.guild.icon_url)
        await channel.send(embed=embed)```
drifting arrow
stoic galleon
#

o yea

valid perch
drifting arrow
drifting arrow