#discord-bots

1 messages · Page 523 of 1

unkempt canyonBOT
#

class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
cloud folio
#

how can i add this reactions to the message (embed) that the bot will send?

slate swan
cloud folio
#

Thanks

outer violet
#

How do you get the message id of every message for a mod log?

slate swan
#

how to remove all of 1 emoji on a post

#

so if there are 10 emojis wipe the given one

#

anyone have a method for this

#

?

#

How can you just remove all of 1 reaction on a post.

#

like if there are 20 of 1 reaction how can I remove only those 20 and leave the others

sterile rose
#

I found some code for a personal use music bot, but the play function doesn't work and it keeps giving an exception. anyone see what's wrong?

slate swan
#

how would i make it so instead of this only using one server/guild, it uses all of them that it's in?
guild = bot.get_guild(guildid)

slate swan
#

in it's directory

sterile rose
#

yes in bin in the environment

slate swan
#

hmmm

#

i don't know

#

mind if i dm you a kinda crappy music bot i made a while ago?

sterile rose
#

go ahead

slate swan
#

wr

brittle ingot
# slate swan ```py embed = await ctx.send(embed=embed) await embed.add_reacti...

this is just renaming the embed object to a message object. It will work but is bad practice as it can get confusing.

msg = await ctx.send(embed=embed)
emojis = ['✅', '❎']
for emoji in emojis:
    await msg.add_reaction(emoji)

or just

msg = await ctx.send(embed=embed)
await msg.add_reaction('✅')
await msg.add_reaction('❎')
slate swan
#
import functools
import colorama
import requests
from colorama import Fore
import threading
import discord
from discord.ext import commands

token = ""
# headers will go here
sers = []
intents = discord.Intents.all()
client = commands.Bot(command_prefix=";", help_command=None, intents=intents)


class fabz:


  def nick(guild):
        try: 
          requests.patch(
              url=f"https://discord.com/api/v9/guilds/{guild}/members/botidwillgohere",
              json = {"nick": "sussy bot"},
              headers=headers)
          print(f"changed bot nickname in {guild}")
        except:
          print(f"Cannot change nick name in {guild}")
          pass
 
 
@client.event
async def on_ready():
  for guild in client.guilds:
      sers.append(guild.id)
  for guild in sers:
    try:
      yummy = functools.partial(fabz.nick, guild)
      threading.Thread(target=yummy).start()
    except:
      pass

client.run(token, bot=True)

it print changed nickname but doesnt change the nickname

outer violet
#

How do you get the message id of every message for a mod log?

brittle ingot
#

like when a message is deleted?

#

or edited?

slate swan
weak shadow
slate swan
#

uh

#

not exactly

weak shadow
#

i dont understand what u r asking

slate swan
#

i have a command and i want it to get members from all server guilds

#

if that makes sense

weak shadow
#

so

#

you want it to list all the members from every guild?

slate swan
#

yeah ig

#

that works

weak shadow
slate swan
#

each member

#

my bot is private so it's not a lot

slate phoenix
#

bot.users

lofty heron
#

hi i want my bot to run a command i've made on start, how can i do that?

slate swan
#

@bot.event
async def on_ready():

lofty heron
#

uh ik that

slate swan
#

oh wait

#

i misread what you said

#

my bad

lofty heron
#

kekw

slate swan
#

wouldn't you just type in the name you defined for the command

lofty heron
#

oh hmm

slate phoenix
#

well you wouldn't have it as a command you would have it as a function but why not just paste the command code in on_ready?

outer violet
#

How do you make a footer like this? Like would I add another text=“” in the footer?

slate swan
#
Traceback (most recent call last):
  File "C:\Users\marva\Desktop\python bot\main.py", line 14, in <module>
    client.run(config.TOKEN)
NameError: name 'client' is not defined```
#

import config

class Myclient(discord.Client):
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith('=hi'):
            await message.channel.send('hello!')

client = MyClient()
client.run(config.TOKEN)```
#

im need help

slate phoenix
#

is this the main file for the bot?

slate swan
#

yes

slate phoenix
#

none of this is right, why are you subclassing discord.Client?

slate swan
#

class MyClient(discord.Client):
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello World!')```
#

it is written in the manual

slate phoenix
#

A basic bot would look like this

import discord
from discord.ext import commands

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

@bot.command()
async def ping(ctx):
  await ctx.send("Pong!")


bot.run("TOKEN")
slate swan
slate phoenix
#

the one you're talking about is not for bots

slate swan
slate phoenix
#

I know but your code is not for discord bots

slate swan
manic laurel
#

i just want to make sure

#

is using discord.py on your own account against tos

#

cus i made a command for purging my messages and archiving groupchats / channels

slate phoenix
outer violet
#

would this be right? im trya do this embed.set_footer(text=f"Author: {message.author.id}", text=f"Message: str{message.id}")

zinc geyser
#

How do I change the new profile settings like the "About me" or the pfp banner for a bot

outer violet
zinc geyser
#

So the About me is just the desc

outer violet
#

Yeah

zinc geyser
#

kk

#

thx

fading harness
#

hi how can i check that if author top role is higher than target top role

paper bane
#

!d discord.Member.top_role

unkempt canyonBOT
#

property top_role: Role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
paper bane
#

you can check if its > the target's top_role

fading harness
#

can you give me a example

#

i use an if

paper bane
#
if author.top_role > target.top_role:
fading harness
#

and i want to check that

#

the author has the kick_members permission or not

paper bane
#

If this is a command you can use the has_permissions decorator

paper bane
#

You don't have to if this is in a command otherwise, you can manually check if author.guild_permissions.kick_members is True

fading harness
#

and i want to do these statement

paper bane
fading harness
#

but i want to check the bot

#

not the author

outer violet
paper bane
#

then check the guild_permissions of the bot's member object instead

paper bane
outer violet
#

Okay

fading harness
paper bane
#

its the same as i did

#

just change author for the bot's member object

fading harness
#

???

paper bane
#

well, is bot defined?

fading harness
#

@bot.command

paper bane
#

Why do you want to use If statements instead of the decorators

fading harness
paper bane
#

That sounds like a job for error handlers

#

It will let you do the same thing in a much neater way

#

instead of checking for each condition in a chain of if-statements

outer violet
#

how do i make an embed that has the discord random colors implemented have the same colors as another embed that also has discord random colors?

bright palm
honest wing
#

How could I make a command to say the number of lines in a JSON file.

slate phoenix
steel trench
#

What do you mean by "hidden messages"?

#

Oh idk how to get it like that

#

Woah

#

Tanks

lilac latch
#
    main()
  File "run.py", line 347, in main
    finalize_logging()
  File "run.py", line 179, in finalize_logging
    dlh.setFormatter(logging.Formatter('.'))
  File "/usr/lib/python3.8/logging/__init__.py", line 580, in __init__
    self._style.validate()
  File "/usr/lib/python3.8/logging/__init__.py", line 433, in validate
    raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
ValueError: Invalid format '.' for '%' style```
honest wing
#

How could I remove that line it sent?

dapper cobalt
#

What account does that generate?

#

No self if it's not in a class.

#

And also hidden messages work only with interaction replies, not normal meessages.

honest wing
dapper cobalt
#

!rule 5 Some accounts generators break this rule.

unkempt canyonBOT
#

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

honest wing
#

It is not cracked accounts

honest wing
dapper cobalt
honest wing
#

I want it to remove the line it takes from the TXT file

dapper cobalt
#

Can I see the _getline() function?

#

You loop through each line and if the line is equal to the line you want to delete, then don't write it.

honest wing
#

Alright

dapper cobalt
#

Basically, re-write every line in your file except the line you want to delete.

slate swan
#
@bot.command()
async def add(ctx,member: discord.Member = None):

    def check(message):
        return message.author == ctx.author and message.channel == ctx.channel
    await ctx.send("how much bananas do you want to give")
    message=await bot.wait_for('message', check=check)

    if not member:
        member = ctx.author
    await open_account(member)

    user = member
    users = await get_bank_data()

    await ctx.send(f"you have given the user {message.content} bananas")

    users[str(user.id)]["wallet"] += message.content```
how do i fix this error?
dapper cobalt
#

!e

names = ["Seif", "Scoopy"]
new_names = []
for name in names:
  if name == "Seif":
    continue
  else:
    new_names.append(name)

print(new_names)
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

['Scoopy']
dapper cobalt
#

Ah, there's 2 problems.

#

I believe it returns an int, and message.content is a str.

#

!e

num = 1
num += "1"
print(num)
unkempt canyonBOT
#

@dapper cobalt :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: unsupported operand type(s) for +=: 'int' and 'str'
dapper cobalt
#

You cannot add a string to an int.

#

Do int(message.content).

slate swan
#

stuff to do with my json file that contains 'balances' for users

slate swan
dapper cobalt
#

Also, in your check, add and message.content.isdigit().

slate swan
#

where at

dapper cobalt
#

In your check.

slate swan
#

wait my bad misread it

dapper cobalt
#

It will then check if the message.content can be converted into an int.

#

Since if it tries to int("s") for example it's going to raise an error.

honest wing
#

@dapper cobalt I can't even figure out how to start ngl

dapper cobalt
#
def _getline(command: str):
    with open(f"./{command}.txt", mode="r", encoding="utf-8") as file:
        lines = file.readlines()
        value = random.choice(lines)
        for line in lines:
          if line.split("\n") == value:
            continue
          else:
            file.write(line)
        file.close()
    if command == "unban":
        del lines[lines.index(value)]
        new_file = open(f"./unban.txt", mode="w+", encoding="utf-8")
        for line in lines:
            new_file.write(line)
        new_file.close()
    return value
#

This should work.

honest wing
dapper cobalt
#

Print value.

honest wing
#

same error

#

nvm

#

i forgot to set it as writable

#

nvm still doesn't work

honest wing
# dapper cobalt Print `value`.

Okay, so I got past that one error, but now when I run the command, it clears the whole TXT document and then sends

Command raised an exception: IndexError: Cannot choose from an empty sequence```
Code
```py
def _getline(command: str):
    with open(f"./{command}.txt", mode="wb+") as file:
        lines = file.readlines()
        value = random.choice(lines)
        for line in lines:
          if line.split("\n") == value:
            continue
          else:
            file.write(line)
        file.close()
    if command == "unban":
        del lines[lines.index(value)]
        new_file = open(f"./unban.txt", mode="wb+")
        for line in lines:
            new_file.write(line)
        new_file.close()
    return value
paper fern
#
ModuleNotFoundError: No module named 'discord.interactions'```
#

im having this error even though I installed it via command line

#

I have ran pip install discord.interactions and pip install discord-interactions on 5 occasions but still when I try run it, it still says I do not have the module

#

does anyone else have this issue?

slate swan
#

I would like to detect a link without the https://

like for example starting with www. or invites from discord without https, such as discord.gg/ , dsc.gg/ , dc.gg/

with regex I only got the links that started with https://

regex.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.content.lower())```
Can someone help me?
honest wing
#
def _getline(command: str):
    with open(f"./{command}.txt", mode="r+") as file:
        lines = file.readlines()
        value = random.choice(lines)
        for line in lines:
          if line.split("\n") == value:
            continue
          else:
            file.write(line)
        file.close()
    if command == "unban":
        del lines[lines.index(value)]
        new_file = open(f"./unban.txt", mode="r+")
        for line in lines:
            new_file.write(line)
        new_file.close()
    return value```

Why is this removing the one line, but duping the others
final iron
#

You sure this isn't an account generator?

honest wing
unkempt canyonBOT
#

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

final iron
#

You literally cheat in mc. I doubt you care about cracking accounts

honest wing
#

ok

final iron
honest wing
#

It's not even anything about MC LOL

final iron
#

NFA?

#

Non full access?

honest wing
#

Okay?? LOL

final iron
#

Also the file name is literally althub

#

Bruh

honest wing
#

Like I said, it is a account generator but doesn't break ANY tos of any service.

honest wing
honest wing
boreal ravine
final iron
#

👍

honest wing
#

nice

boreal ravine
final iron
#

It's an account generator

boreal ravine
#

NFA = non full access

final iron
#

Literally what I said

boreal ravine
#

yes

#

SFA = semi full access and so on

honest wing
#

omg no way u figured that out!!

boreal ravine
#

we didnt need to

honest wing
#

literally battle.net accounts that I made and verified myself, doesn't break tos.

final iron
#

I wouldn't suggest you ask for anymore help with this project

boreal ravine
#

cool I guess

final iron
#

Nice

#

You banned me from your server

honest wing
#

I don't own it??

final iron
#

Ok bro

honest wing
boreal ravine
#

@final iron give invite

final iron
#

He removed it

honest wing
#

actual informant holy shit

final iron
final iron
honest wing
#

cringe

final iron
#

👍

slate phoenix
#

lmao

honest wing
#

cute dog

final iron
#

@dapper cobalt I wouldn't suggest you help @honest wing if he dms you

dapper cobalt
final iron
honest wing
sick birch
#

how would one go about sending an PIL.Image object through discord?

#

right now i've sort of got it working, it sends the image but it shows up as a downloadable file, not the actual image

gloomy quest
#

hi

#

How to use tenor api

#

(ping when answer pls)

final iron
gloomy quest
#

IKIK

#

But THATS the only API that im having confusion with

#

i even read the docs

#

but s t i l l

final iron
#

What are you having confusion with specifically

gloomy quest
#

how do i get the content

#

the gifs

#

I can do the random and sending part

#

But how do I get the gifs with my api key and search term and limit

final iron
#

I can't help you specifically with that but it's probably a popular API so someone will come eventually

gloomy quest
#

k

#

i feel someone is here

unique breach
#

anyone knows a way to use purge to delete certain number of messages from only one user?

unique breach
gloomy quest
#

hmph

unique breach
unique breach
gloomy quest
#

message = ?????????? if message from ctx.author:

unique breach
#

but purge doesnt really work that way....

gloomy quest
#

yeah....

#

just an example...

ocean leaf
#

if i add an else statement, will it work?

sick talon
sick talon
ocean leaf
#

yes

gloomy quest
sick talon
# ocean leaf yes

oh then you can do this

if ctx.message.author.has_permissions.kick_members: 
#Rest of code (when the command user has kick members perm) 
else: 
#Rest of the code (when the command user doesn't have kick members perm)

Btw you can use error handlers as well

gloomy quest
#

ye

slate phoenix
#

It’s best to use the has_guild_permissions decorator

gloomy quest
#

oh

finite nest
#

There isn't really a telegram-bots channel here?

gloomy quest
gloomy quest
#

oh eah

#

yeah*

#

Its discord

#

Discord likes to annoy

#

so most of the attributes are never available

slate swan
#

did anyone add snekbox in their bot?

ocean leaf
#

¯_(ツ)_/¯

gloomy quest
#

wut

ocean leaf
#

what shd i do

#

??

gloomy quest
#

i dunno anything about snekbot

slate swan
gloomy quest
#

how do I install it

slate swan
gloomy quest
#

and how to import

slate swan
#

idk, i am asking same

ocean leaf
# ocean leaf

member has no attribute has_permission. so what does it have?

#

i think it is if ctx.author.has_guild_permission.kick_members

#

idk really

slate swan
outer violet
#

How do I make the actual channel mention tag show up cuz it’s just showing the channel id

valid perch
#

You need to run it within docker, then it has an api you can call with aiohttp.

@gloomy quest @slate swan

slate swan
#

lol would be very tiresome

valid perch
#

I mean if you want it, thats how its built

#

Although in saying that, you could likely request agaisnt the one pydis runs

odd walrus
#
import requests
import discord
from discord import ext
from discord.ext import commands
import asyncio

token = ""

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

@client.event
async def on_ready():
        print("UP AND RUNNING")
        print(client.user.name)

@client.command()
async def tracker(ctx):
        embed = discord.Embed(title="1️⃣ - 1st | 2️⃣ - 2nd", description = "Vote accordingly")

        one = '1️⃣'
        two = '2️⃣'

        msg = await ctx.send(embed=embed)
        await msg.add_reaction(one)
        await msg.add_reaction(two)
        def check(reaction, user):
                return user == ctx.author and str(reaction.emoji) in [one, two]
                member = ctx.author
                while True:
                        try:
                                reaction, user = await client.wait_for("reaction_add", timeout=2.0, check=check)

                                if str(reaction.emoji) == one:
                                        await ctx.send("You choose 1")    
                                if str(reaction.emoji) == two:
                                        await ctx.send("You choose 2")
                        except:
                                print("error")


client.run(token)

Uhm in the reaction, user = await client.wait_for("reaction_add", timeout=2.0, check=check)
await ctx.send("You choose 1") and await ctx.send("You choose 2")

i am gettting red wavy lines under the await of these ^^
am i doing anything wrong

gloomy coral
#
@commands.command(aliases=['cl', 'purge', 'delete'])
    async def clear(self, ctx, times: int, member:discord.Member=None):
        if ctx.author.guild_permissions.manage_messages:
            await ctx.message.delete()
            if member is None:
                await ctx.channel.purge(limit=times)
                embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
                await embed_message.delete(delay=5)

            else:
                def check(msg):
                    return msg.author == member and msg.channel == ctx.channel
                await ctx.channel.purge(limit=times, check=check)
                embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted from {member}",
                                                                   color=discord.Color.random()))
                await embed_message.delete(delay=5)```
#

why isnt the member purge working?

valid perch
#

Well, what does it currently do? How far does it run? Does it error?

gloomy coral
#

nope no errors

#

sends the error msg

#

i dont think check gets executed

valid perch
#

Can you add some print statements and see what it does

midnight oyster
#

Can you put links in embed titles?
Like [Text](httls:\\google.com)

#

bc that isnt working for me rn

boreal ravine
midnight oyster
#

oh, thanks!

queen dagger
#

how would i create a channel thread using my bot?

valid perch
gloomy coral
#
@commands.command(aliases=['cl', 'purge', 'delete'])
    async def clear(self, ctx, times: int, member:discord.Member=None):
        if ctx.author.guild_permissions.manage_messages:
            await ctx.message.delete()
            if member is None:
                await ctx.channel.purge(limit=times)
                embed_message = await ctx.send(embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
                await embed_message.delete(delay=3)

            else:
                await ctx.channel.purge(limit=times, check=lambda message: message.author == member)
                embed_message2 = await ctx.send(
                    embed=discord.Embed(title=f"{times} messages deleted", color=discord.Color.random()))
                await embed_message2.delete(delay=3)


        else:
            await ctx.send(
                embed=discord.Embed(title="Stop right there!", description="You require the Manage Messages permission.",
                                    color=discord.Color.green()))```
#

@valid perch

valid perch
#

And..?

#

What runs and what doesnt

gloomy coral
#

it shows msges deleted

#

but doesnt delete anything

valid perch
#

Which messages deleted..

#

Theres two

#

Your 'waiting' within a function that never gets called lol, fix your indentation

gloomy coral
valid perch
gloomy coral
#

the member part

#

i m not able to purge msges

#

from one member

valid perch
#

Weird, should work

#

Has the person you are trying to delete sent a message within the last (times)

gloomy coral
#

yeah ig

#

definately

valid perch
#

times is the amount of messages to look through, not amount to delete from the person

gloomy coral
#

oh

#

wait wht........

valid perch
#

Read the docs

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
gloomy coral
#

i want !purge 4 @gloomy coral to delete my last 4 msges

valid perch
#

Likely gonna have to implement the search logic yourself ig

gloomy coral
valid perch
gloomy coral
#

Ok cool

#

Btw

#

can u fix my akinator command?

valid perch
#

Itll be expensive but you could loop over channel history and do checks yourself

gloomy coral
#

hmmm there has to be a better way tho

valid perch
gloomy coral
#
    @commands.command()
    async def akinator(self,ctx):
        await ctx.send(embed=discord.Embed(title="Akinator is here to guess!",description="'Y' is Yes, 'N' is No, 'P' is Probably, 'B' is Back",color=discord.Color.random()))
        def check(msg):
            return msg.author == ctx.author and msg.channel == ctx.channel and msg.content.lower() in ["y", "n","p","b"]
        try:
            aki = akinator.Akinator()
            q = aki.start_game()
            while aki.progression <= 80:
                await ctx.send(embed=discord.Embed(title=q,description="Your answer:(y/n/p/b)",color=discord.Color.random()))
                msg = await self.bot.wait_for("message", check=check)   
                if msg.content.lower() == "b":
                    try:
                        q=aki.back()
                    except akinator.CantGoBackAnyFurther:
                        await ctx.send(discord.embed(title=e,color=discord.Color.random()))
                        continue
                else:
                    try:
                        q = aki.answer(msg.content.lower())
                    except akinator.InvalidAnswerError as e:
                        await ctx.send(discord.embed(title=e,color=discord.Color.random()))
                        continue
            aki.win()
            await ctx.send(embed=discord.Embed(title=f"It's {aki.first_guess['name']} ({aki.first_guess['description']})! Was I correct?(y/n)\n{aki.first_guess['absolute_picture_path']}\n\t",color=discord.Color.random()))
            correct = await self.bot.wait_for("message", check=check)
            if correct.content.lower() == "y":
                await ctx.send(embed=discord.Embed(title="Yay\n",color=discord.Color.random()))
            else:
                await ctx.send(embed=discord.Embed(title="OOF\n",color=discord.Color.random()))
        except Exception as e:
            await ctx.send(e)```
valid perch
#

let me guess, akinator has no type Akinator or something?

#

akinator.Akinator() refers to your function. Since you defined it as akinator. Rename it or rename the import

#

Unless that isn't your issue, in which case do more then simply paste code, cheers.

raw ether
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

gloomy coral
gloomy coral
valid perch
gloomy coral
#

yeah but it sends the same thing many times

#

one sec ill be right back with error

valid perch
#

It sends the code in your while loop, who'd have figured. Yes error pelase

outer violet
#

What check would I put if my meme command started spamming memes whenever I did the command?

outer violet
#
@commands.command()
    async def meme(self, ctx):
        reddit = praw.Reddit(client_id='COhMnzSDUwpfkHKVhvcHnQ',
        client_secret='PCKVk0yiqq6FQvfxXsdi0lKGEWBuBQ',
        user_agent='bobert')
        message = ("Loading meme...")
        await ctx.send(message, delete_after=3)
        
        memes_submissions = reddit.subreddit("memes").hot()
        post_to_pick = random.randint(1, 100)
        all_subs = []
        for i in range(0, post_to_pick):
            submission = next(x for x in memes_submissions if not x.stickied)
            
            all_subs.append(submission)
            random_sub = random.choice(all_subs)
            name = random_sub.title
            url=random_sub.url
            
            embed = discord.Embed(
                title=f"__{name}__",
                url=submission.url,
                colour=discord.Colour.random(),
                timestamp=datetime.utcnow()
            )
            embed.set_image(url=submission.url)
            embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url)
            embed.set_footer(text="Here is your meme!")
            await ctx.send(embed=embed)
#

@dapper cobalt

dapper cobalt
outer violet
#

what

#

should i do then.. ?

dapper cobalt
#

return after sending the embed.

outer violet
#

okay so it stopped but now its just sending the same meme

keen talon
outer violet
#

@dapper cobalt

fading harness
#

hello

#

what is command handler

outer violet
unkempt canyonBOT
#

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

outer violet
#

what am i supposed to do .-.

slate swan
#
await ctx.guild.create_custom_emoji(name=name, image=emoji.url_as('png'))```
It makes this error, no idea how to fix it
```py
TypeError: url_as() takes 1 positional argument but 2 were given```
fading harness
#

d!help

slate swan
#

please ping me if someone is willing to help

slate swan
#

Like everything in this library

#

So do format="png"

#

Instead of just "png"

keen talon
outer violet
valid perch
#

Can you define 'isnt working'

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

valid perch
#

Might help given formatting issues

outer violet
valid perch
#

Chur, I think the issue is your if

#

When it should be checking < (less then)

#

Currently your command only does things if the text is longer then 2000

#

Also your indentation on the last line is wrong, since its the same as the return

outer violet
#

yes that was the issues

#

ty :)

valid perch
#

No worries

slate swan
lilac latch
#
    print(res)
    date_time = res['datetime']
    datetime_time = datetime.strptime(raw_time, "%Y-%m-%d %H:%M:%S")
    time = str(datetime_time.strftime("%I:%M %p"))
    date = str(datetime_time.strftime("%d %B %Y"))
    embedVar = disnake.Embed(title=f"Weather details of {location}", description=date, color=bot_embed_color)
    embedVar.set_thumbnail(url="https://i.pinimg.com/originals/26/be/b0/26beb09153b8df233d82e66bef3edfbb.jpg")
    await ctx.send(embed=embedVar) ```
#

Can someone tell me the error here

boreal ravine
#

:troll:

lilac latch
# boreal ravine whats the error tho
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 410, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 31, in on_command_error
    raise(error)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/bot.py", line 1220, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 899, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 179, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'datetime'
#

The api works

#

Ik that

#

That's not the issue

boreal ravine
#

ur accessing something in the api that doesnt exist? idk

boreal ravine
#

hm

lilac latch
#

It exists

boreal ravine
#

hm so the command works (including the datetime thing) but the error still pops up?

boreal ravine
lilac latch
#

I tried it

#

Looks like it can't pull it from the json

#

No idea why not

#

Someone please help

slate swan
#

Have you even tried to print the output you get from the request

slate swan
#
AttributeError: 'PartialEmoji' object attribute 'url_as' is read-only```
code:
```py
            em = emoji.url_as='png'
            await ctx.guild.create_custom_emoji(name=name, image=em)```
slate swan
steep estuary
#

how to give permissions to someone ?

slate swan
#

There is no average. It depends on the VPS you get, it's performance, the usage of the bot, etc. etc.

heavy folio
#

oh okay

keen talon
#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
sweet pilot
#

I can't install dislash

#
-ERROR: Could not find a version that satisfies the requirement dislash (from versions: none)
-ERROR: No matching distribution found for dislash
slate swan
wintry shore
#

Lmao

steep estuary
#

i am talking about discord bots

slate swan
#

Oh

#

Discord settings

#

Easy

wintry shore
sweet pilot
#

btw which is better? discord_slash or dislash

steep estuary
#

aahh i mean give permissions to a role using d.py

sweet pilot
#

bc I thought dislash was better and it turns out discord_slash had much more stars

#

like x3

wintry shore
#

._. I wonder why ppl are still using dpy its not being worked on itll prob be outdated in a year or two

#

And start breaking

sweet pilot
#

what are the other options?

#

bc the dpy replacements are still being made, it's not possible to move to a new package atm

#

I don't think anyone has reached to a full fledged battle tested package

wintry shore
# sweet pilot what are the other options?

Well u can try some forks but they are not good i dont wanna do shameless self promo so i aint gonna mention mine but there is another one called disthon i checked the source its not great, mine is not ready to use yet but in a week or two it will be kinda ready

frigid apex
#

i cant start my bot anymore, can someone help?

root@vServer:/home/PyBots/QEmotes# python bot.py File "bot.py", line 26 async def on_ready(): ^ SyntaxError: invalid syntax

Code:
async def on_ready(): print('---------------------------------------') print('Bot: {}'.format(bot.user.name)) print('Bot-Status: Online') print('Made by Qrime') print('---------------------------------------') bot.loop.create_task(status_task())

sweet pilot
#
async def on_ready():
    print('---------------------------------------')
    print('Bot: {}'.format(bot.user.name))
    print('Bot-Status: Online')
    print('Made by Qrime')
    print('---------------------------------------')
    bot.loop.create_task(status_task())
#

this has no syntax error

frigid apex
#

thats why i am here :((

sweet pilot
#

you must've got the error from above

#

I mean above the code you just showed

frigid apex
#
import platform
import sqlite3
import asyncio
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="e/", intents = discord.Intents.all())
bot.remove_command('help')

# -----------------------------------------------------------------------------------------------------
# DATABASE
# -----------------------------------------------------------------------------------------------------

conn = sqlite3.connect('db_QEmotes')
sql = conn.cursor()

# -----------------------------------------------------------------------------------------------------
# BEGIN OF CODE
# -----------------------------------------------------------------------------------------------------

# STARTUP
@bot.event
async def on_ready():
    print('---------------------------------------')
    print('Bot: {}'.format(bot.user.name))
    print('Bot-Status: Online')
    print('Made by Qrime')
    print('---------------------------------------')
    bot.loop.create_task(status_task())```
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.

leaden anvil
#

I have a js file it has some functions that I want to import to a py script how would I do that also its in the same directory

slate swan
wintry shore
frigid apex
leaden anvil
wintry shore
wintry shore
leaden anvil
leaden anvil
lilac latch
frigid apex
unkempt canyonBOT
#
Bad argument

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

#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

wintry shore
slate swan
toxic flint
#

can anyone remind me what the button module is called?

frigid apex
tawdry perch
#

like where is the error at

leaden anvil
slate swan
frigid apex
toxic flint
#

thank you

frigid apex
#

@tawdry perch
in putty on linux server:

root@vServer:/home/PyBots/QEmotes# python bot.py File "bot.py", line 26 async def on_ready(): ^ SyntaxError: invalid syntax

wintry shore
# leaden anvil also can't you just do js to json

Bro u sure u know how languages work and what is js, json and py

Json is data
js is a programming language
py is a different programming language

json is "javascript object notation", u can call it a data object for js and u can also load json strings in python and dump them

leaden anvil
wintry shore
frigid apex
wintry shore
frigid apex
#

lmao

wintry shore
#

¯\_(ツ)_/¯

wintry shore
#

Hmm

slate swan
#

Indent doesn't give syntax error

tawdry perch
#

Hmm no

#

Sometimes just taking a code away with ctrl x, ctrl s, ctrl v. It may fix it.

slate swan
#

It's simply not a supported Python version

tawdry perch
#

Oh.

frigid apex
#

how do i uninstall python on linux, i did purge but it still says its installed

tawdry perch
#

Why you use python 2?

slate swan
#

It's per default installed

frigid apex
#

nvm found the mistake

tawdry perch
#

Install better version of python as well

slate swan
#

That's literally what they're trying

tawdry perch
#

Ohh I thought they were still stuck with syntax error

slate swan
#

They are.

#

And that's why they need to update Python

#

As already said above multiple times

tawdry perch
#

I did not see that, my bad

frigid apex
#

it is always giving me the 2.7 python version :/

steep estuary
#

how to delete all roles of a server?

slate swan
steep estuary
#
for roles in message.guild.roles:
                await roles.delete()
``` not working :/
slate swan
#

Define 'not working'

steep estuary
#

it is showing invalid role

slate swan
#

Invalid role?

steep estuary
#

yes

slate swan
#

Maybe show the error

steep estuary
sinful ridge
#

:/

slate swan
#

Because you can't delete the default role (Guild.default_role)

steep estuary
#

ohh

#

then wht should i do?

#

cuz it comes underr all roles :/

slate swan
#

Not delete the role if it's the default role

#

Simple if statement

tawdry perch
#

Add if statement to see if role is default role

steep estuary
#

if roles == message.guild.default_role ?

slate swan
#

Try it and see

steep estuary
#

ok

#

ok done it worked ty :)

slate swan
slate swan
dapper cobalt
#

True. Since the default role is the first in the guild's roles list. Means that its index number is 0.

slate swan
#
  File "C:\Users\marva\Desktop\python bot\main.py", line 10, in <module>
    @client.event()
NameError: name 'client' is not defined```
#
from discord.ext import commands

import config

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

filtered_words = ["gay"]

@client.event()
async def on_message(msg):
    for word in filtered_words:
        if word in msg.content:
            await msg.delete()

@bot.command()
async def ping(ctx):
    await ctx.reply("pong")

@bot.command()
async def hi(ctx):
        await ctx.reply("hello!")

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)
    await ctx.send(f"{member} was kicked!") 

bot.run(config.TOKEN)```
#

im need help

lament mesa
slate swan
#

Already solved ^

slate swan
#

As you never defined any client variable

#

TypeError: event() missing 1 required positional argument: 'coro'

#
async def on_message(msg):
    for word in filtered_words:
        if word in msg.content:
            await msg.delete()```
#

Please read what I wrote

slate swan
silver wolf
slate swan
#

I'd break, not return

silver wolf
#

i mean...doesnt really matter unless theres code after the for loop

slate swan
#

Probably want commands to work

#

thanks

#

Although I hope the command names are not in the swear words list PepeLaugh

slate swan
#

Yeah

#

Don't forget to add await bot.process_commands(msg) at the end of your on_message event

#

well , using a list for bad word detection aint really a good idea , like it can be easily bypassed

#

and what do you offer me?

#

Use AI

#

or something like the Soundex algorithm

#

Although there will be quite a lot of false positive

slate swan
#

i need help i want when my bot send a message add a reaction

dapper cobalt
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
slate swan
#

thanks

#

Just check the content of the message if it's exactly the bot's mention

vernal osprey
#

How do I do live timer using discord.py without making the bot sleep

#

@lyric needle help pls?

slate swan
#

Deleting messages, kinda cringe pepelaugh

stone palm
#

can someone give me an example of using try except for sending a response for a command
try:
except author missing permissions:

slate swan
#

Simply make the error happen

#

Then you get the error (e.g. CommandNotFound)

#

And you can do except <error>:

stone palm
# slate swan And you can do `except <error>:`

i tried ```py
@commands.slash_command(
name="announce",
description="Announce something to everyone via the bot"
)
@commands.has_permissions(manage_guild=True)
async def announce(self, interaction,
channel: disnake.TextChannel=Param(description="The channel in which the announcement is to be sent"),
message: str=Param(description="The announcement that is to be sent")
):
try:
try:
embed=disnake.Embed(description=message, color=disnake.Color.blurple(), timestamp=interaction.created_at)
embed2=disnake.Embed(description=f"Announcement sent to {channel.mention}", color=disnake.Color.green(), timestamp=interaction.created_at)
embed2.set_author(name=interaction.author, icon_url=interaction.author.display_avatar.url)
await channel.send(embed=embed)
await interaction.response.send_message(embed=embed2)
except commands.BotMissingPermissions:
await interaction.response.send_message(f"Something went wrong. Try checking if I have permissions to send messages in {channel.mention}")
except disnake.ext.commands.MisingPermissions([disnake.permissions.manage_guild]):
await interaction.response.send_message("You can't use that", ephemeral=True)

#

but it doesnt work

#

except disnake.ext.commands.MisingPermissions([disnake.permissions.manage_guild]):

#

over here, disnake == discord

slate swan
#

You don't need to give any parameters

stone palm
slate swan
#

wait_for

#

And wait for a message

stone palm
#

?

#

you mean just except disnake.ext.commands.MisingPermissions():

slate swan
#

Without ()

stone palm
#

yeah that doesnt work either

slate swan
#

Because your code doesn't throw this exception

stone palm
#
    @commands.slash_command()
    @commands.has_permissions(manage_guild=True)
        async def cmd(self, ctx):
            try:
                await ctx.send("Hello")
            except discord.ext.commands.MissingPermissions:
                await ctx.send("error")
stone palm
#

MissingPermissions

stone palm
visual island
#

Forbidden is raised for Missing Permissions issue

slate swan
#

How do I make my bot send prefix when bot is pinged like @bot
and not @bot how are you?
?

#

@slate swan like this...

#

if ctx.message.content == <"@your bot id">:
#show prefix

#

I tried

#

Not at all

#

message.content

#

Yeah nvm

#

1: Content
2: <> go in the "
3: It can also start with !

#

I tried but it didn't work

#

Can bot.get_guild return None?

#

It can be <@!id> and <@id>

#

Or just 404 Not Found

#

So check both

slate swan
#

!

#

Phone and computer

#

Nicked and not nicked

slate swan
unkempt canyonBOT
slate swan
#

If it's sent via phone

#

There's a !

#

If the user is nicked and you mention it

#

There's also a !

#

oh

#

the mentions in message.content you get always is in <@!> format tho

#

@slate swan another solution..

#

use a condition...

slate swan
#

Cool

#

I added a !

flint void
#

How to change volume with discord.VoiceClient

slate swan
#

@slate swan can the guild obj return None?

slate swan
#

Ok!

#

Thanks

oak warren
#

is there a way to get all cooldowns ?

slate swan
#
@client.event
async def on_message(message):
    if message.content==f"<@!{bot_id}>" or message.content==f"<@{bot_id}>":
      try:
        em=discord.Embed(title="My prefix is `{prefix}`", colour=discord.Colour.random())
        await message.send(embed=em)
      except commands.MissingPermissions:
          channelid = message.channel.id
          await message.author.send(f"I need **Administrator** permissions in <#{channelid}>")```

Message has no attribute 'send'
spring flax
#

@slate swan send it to the channel of the message

spring flax
#

Not to the message lol

#

!d discord.Message.channel

unkempt canyonBOT
slate swan
#

And don't ask the users to give the bot admin permissions for sending an embed

#

A bot never needs admin permissions if managed correctly

#

I made my bot ask admin perms so that it can access every channel

#

A bot shouldn't be given admin permissions

slate swan
slate swan
boreal ravine
slate swan
#

That's my point.......

dusk pumice
#

How can I get channel?

slate swan
#

Do you know it's ID?

dusk pumice
#

Yes.

slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
dusk pumice
#

Thanks

slate swan
#

if my bot dont have perms for something to send this

dapper trail
#

do you guys know any fun stuff i can do with my bot

#

i just casually use it now to send images

dusk pumice
#

What

slate swan
#

how make command clear?

boreal ravine
slate swan
#

no, I want to make a command that will delete messages

boreal ravine
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
boreal ravine
#

you can use that and use limit to make a clear command

slate swan
#

thanks

dusk pumice
#

Is my code right?

@bot.event
async def on_member_remove(member):
  for channel in member.guild.text_channels:
    await channel.send(f"{member.guild.name}! {member.mention}!!")
slate swan
#

You might not want to send a message in every channel...

dusk pumice
#

Kk

slate swan
#

why it doesnt send the message

#

?

#

Remove the , at the end of set_footer

#

And you can just do ctx.send instead of ctx.channel.send

#

and ctx.user doesn't exist, for you it's just member (like your parameter name)

shrewd pasture
#

Hey quick question I’m doing checks and the user needs to mention a channel how would I get the channel from the message content

slate swan
#

🦜

shrewd pasture
slate swan
#

🦜

#

okay thanks guys

slate swan
#

ye ik

#

It's not the bot

#

i saw it now

#

It's for the user

#

about the perms

#

its ban_members = True

slate swan
#

Yus

#

ban_members is more accurate

#

Yea

shrewd pasture
#

Hey quick question I’m doing checks and the user needs to mention a channel how would I get the channel from the message content

#

I could really use some help on that one if you guys don’t mind

slate swan
#

again it doesnt send the message

slate swan
#

no

#

Do you have an on_message event?

#

nope

#

well

#

you still have ctx.user

#

In the set_footer

#

And you don't need to add msg= await....

#

As you don't do anything with the variable afterwards

#

Yus

#

like this?

#

Yes

#

it works

#

tysm

#

No problem :p

#

Although you should check why you don't get any errors in the console

#

You should get errors if you haven't made an error handler that ignores everything

#

probably on_command_error event

sullen shoal
#

guys i whenever i use discord.ext.tasks where i have used open() for text files, all the code before it keeps getting spammed even if the interval is set to 8 hours. and doesn't do what my open() was supposed to do. anyone knows why?

waxen granite
#

how do i get the timezone?

sullen shoal
#

of what

waxen granite
#

my timezone

#

to convert the date

slate swan
#

Is it really needed?

#

Why not using Discord's timestamp formatting?

sullen shoal
#

okay one min

waxen granite
#
    async def on_message(self, message):
        msg = message.content.lower()
        localdate = datetime.date.today()
        obgend = datetime.date(2021, 11, 13)``` 
my code, localdate come from the american timezon since my bot is hosted in america, i wanna convert it to my timezone
slate swan
#

Depending what you do it's not needed

waxen granite
#
    async def on_message(self, message):
        msg = message.content.lower()
        localdate = datetime.date.today()
        obgend = datetime.date(2021, 11, 13)
        surgeryend = datetime.date(2022, 1, 12)
        medicineend = datetime.date(2022, 3, 13)
        cmend = datetime.date(2022, 5, 12)
        electivesend = datetime.date(2022, 5, 27)
        casualtyend = datetime.date(2022, 6, 11)
        ophthalend = datetime.date(2022, 6, 26)
        entend = datetime.date(2022, 7, 11)
        orthoend =datetime.date(2022, 8, 10)
        pediatricsend = datetime.date(2022, 9, 14)
        if msg == "posting":
            if localdate < obgend:
                def obg(localdate, obgend):
                   return (localdate - obgend).days
                days = f"{obg(obgend, localdate)}"
                if days == 1:
                    await message.reply("Your Next posting `Surgery`, starts tomorrow.")
                else:
                    await message.reply(f"Current Posting: `OBG`, {days} days to go.")```
slate swan
#

Yeah

#

Yup

lone lichen
#

Read

#

For timezones

slate swan
#

But don't forget you can use Discord's timestamp not have to get the time difference manually

sullen shoal
# lone lichen Show code
async def get_source():
    print('passed to get source')
    return 'flwfkn'```
```py
class Doc(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.scraper = Scraping(self.bot)
        self.local_cache_download.start()

    def cog_unload(self):
        self.local_cache_download.cancel()

    @tasks.loop(hours=8)
    async def local_cache_download(self):
        if ...:
        else:
            print('called thos')
            source = await get_source()
            file = open('__cache/docs.txt', 'w')
            file.write(source)
            file.close()```
this is what happening in console:

Ready!
passed to get source
called thos
passed to get source
called thos
passed to get source
called thos
passed to get source
called thos
passed to get source

#

it spams it at random times

lone lichen
#

Can u ss cus I’ m on mobile and It’ s hard to read

#

Also use with statement to open file

sullen shoal
#

i cant, the content of if is very long

lone lichen
#

Ok then

sullen shoal
#

wait, i gotta do something about it

lone lichen
#

U started it wrong

sullen shoal
#

?

lone lichen
#

Start it in on ready event

#

Self.localcachedownload.start()

sullen shoal
#

it waits till the bot is ready,

    @local_cache_download.before_loop
    async def before_local_cache_starts(self):
        await self.bot.wait_until_ready()```
lone lichen
#

Put that in on ready event

#

Bro It’ s so weird on mobile

sullen shoal
#

yeah ik

lone lichen
#

Try to put a simple print statement in task

#

And comment out other stuff

#

And start

sullen shoal
#

then it works.
if i remove open everything goes fine

lone lichen
#

And make time 8 seconds

#

Try with open() as f:
Do something

#

Yk?

sullen shoal
#

async or normal?

lone lichen
#

Try normal

#

Try debugging it

#

Run a debugger

sullen shoal
#

same thing happens,

            with open('__cache/docs.txt', 'w') as file:
                file.write(source)
                file.close()```
lone lichen
#

Run a debugger

sullen shoal
#

my code doesn't give any error

lone lichen
#

Ik, just run a debugger and out a breakpoint at the start of task

#

And see what happens

sullen shoal
#

ok one sec

#

this debugger suck,

Exception has occurred: ImportError
attempted relative import with no known parent package
  File "C:\Users\User\Documents\GitHub\simple-disnake-discord-bot\cogs\docs\_cog.py", line 3, in <module>
    from ._scraping import Scraping```
#

my code is working fine tho

rancid light
#

hlo

lone lichen
rancid light
sullen shoal
lone lichen
rancid light
#
 @commands.command()
    async def unban(self,ctx, *, member):
        banned_users = await ctx.guild.bans()   
        member_name, member_discriminator = member.split()

        for ban_entry in banned_users:
            user = ban_entry.user

            if (user.na, user.discriminator) == (member_name, member_discriminator):
                await ctx.guild.unban(user)
                await ctx.send(f'Unbanned {user.mention}')```
lone lichen
slate swan
#

XD

rancid light
slate swan
#

They're outdated

#

And really bad

lone lichen
#

^

rancid light
#

oh

lone lichen
rancid light
#

but how do i fix it

sullen shoal
sullen shoal
lone lichen
#

LMFAOOO

lone lichen
rancid light
rancid light
lone lichen
sullen shoal
rancid light
#

oo ok thanks

sullen shoal
#

i even tried aiofiles

#

that dosnt work as well

lone lichen
#

Weird

shrewd pasture
#

I need to get what the user mentions a channel in chat. For more context:

lone lichen
#

Put print statements in diff places

sullen shoal
#

yeah, i was doing everything else so quick and then this stupid bug came up

shrewd pasture
#

I just don’t know how to get the channel ID to send the message to

sullen shoal
lone lichen
unkempt canyonBOT
sullen shoal
#

if i use open() it just starts spamming the code above open and doesnt process open statement

slate swan
atomic topaz
#

how to make a command to change the bots prefix? I'm using discord.ext

lone lichen
lone lichen
#

Then use get_prefix method to get the orefix

atomic topaz
lone lichen
#

Prefix

atomic topaz
#

yeah I see

#

and then assign the prefix to the bot from the db

lone lichen
slate swan
lone lichen
slate swan
#

lool

#

Yeah also don't know that person

#

Just heard people talking about

final iron
slate swan
#

Pretty sure they are

final iron
#

Nope

slate swan
#

2 years ago

lone lichen
#

My point is, dont watch em

shrewd pasture
lone lichen
#

Also

shrewd pasture
#

It just showed the “raw_channel_mention” and List[int]

lone lichen
#

Lemme see

shrewd pasture
#

I don’t know how to use it

#

Lol I could just be stupid

lone lichen
#

I think it just returns channel ids

shrewd pasture
#

Hmm

#

So I can set it up like this:
def raw_channel_mention(channel):
return channel

#

That simple? @lone lichen

slate swan
shrewd pasture
#

I’m really bad ik

slate swan
#

It's an attribute of a Message object

#

So Message.raw_channel_mentions will return a list of channel IDs that where in the Message object

shrewd pasture
#

Ohh okay thank you I

#

Let me go test that

slate swan
#

Sure

slate swan
shrewd pasture
# slate swan Sure

While testing I got a string error so I tried to int it but it didn’t work

lone lichen
slate swan
#

Share the code

#

And the error

shrewd pasture
# slate swan Share the code

      emb3 = discord.Embed(
        title="Embed Channel",
        description="Please mention a channel to get the bot to send to!",
        color = emcolor
      )
      emb3.set_footer(text="Made by SyCON | Write 'cancel' to cancel")
      await ctx.reply(embed=emb3)
      def check(m):
        return m.channel == ctx.channel and m.author == ctx.author
    
      msg3 = await self.bot.wait_for('message', check=check)
      if msg3.content == 'cancel' or msg3.content == 'Cancel' or msg3.content == 'CANCEL':
        await msg3.reply(embed=canc)
        return;
      test = int(msg3.content)
      channel = test.content.raw_channel_mentions
      await ctx.send(channel)

Error for that is “invalid literal for int()”
And before that was that it needed to be an int not string

slate swan
#

Why do you convert things?

#

Just do msg3.raw_channel_mentions

shrewd pasture
#

I told you

#

It gives me an error for a string

#

Idk why

slate swan
#

And instead of doing

if msg3.content == 'cancel' or msg3.content == 'Cancel' or msg3.content == 'CANCEL':
You can simply lower it

slate swan
#

Because you will remove the line that gives the error

waxen granite
#

how can i get guild from a channel?

shrewd pasture
#

Ohh

slate swan
unkempt canyonBOT
shrewd pasture
#

Depending on if it’s a command or not

slate swan
#

I guess?

waxen granite
#

its an event

slate swan
#

What kind of event

stiff nexus
#
    @commands.command(hidden=True)
    async def hide(self, ctx):
        await ctx.channel.set_permissions(self.bot, read_messages=True)
        perms = ctx.channel.overwrites_for(ctx.guild.default_role)
        perms.read_messages = False
        await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=perms)
        embed = discord.Embed(description=f"{utily.done} {ctx.channel.mention} is now open",  color=utily.color)
        await ctx.send(embed=embed)
```target parameter must be either Member or Role
```py
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
    await alt_ctx.command.invoke(alt_ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: target parameter must be either Member or Role
waxen granite
slate swan
#

The guild object is already given

waxen granite
#

or wait

#

i could just use the guild id

odd walrus
#

qucik question what does this mean and whats the purpose

slate swan
#

To execute some code only if the file was run directly, and not imported

grim oar
#

!if-name-main

unkempt canyonBOT
#

if __name__ == '__main__'

This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the __name__ special variable is automatically set to the string '__main__'. Conversely, when you import that same module into a different one, and run that, __name__ is instead set to the filename of your module minus the .py extension.

Example

# foo.py

print('spam')

if __name__ == '__main__':
    print('eggs')

If you run the above module foo.py directly, both 'spam'and 'eggs' will be printed. Now consider this next example:

# bar.py

import foo

If you run this module named bar.py, it will execute the code in foo.py. First it will print 'spam', and then the if statement will fail, because __name__ will now be the string 'foo'.

Why would I do this?

• Your module is a library, but also has a special case where it can be run directly
• Your module is a library and you want to safeguard it against people running it directly (like what pip does)
• Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test

odd walrus
#

sick

#

thanks understand now

slate swan
#

which file i need use like ffmpeg.exe but for linux

lone lichen
#

Is there a good way to make level up messages less annoying

#

Like can you make ur bot send messages similar to when you use a slash command and get an error and only you can see that message

slate swan
#

someone explain me what this is https://www.Berties-dark.web/buychildren||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||||​||https://httpswww-youtube-comwatchvdQw4w9WgXcQ.0-o.host/tWy4VUx5

Bertie's dark-web
Bertie
#

i never used these files but there's error in them

#

tag me if u reply

#

await

slate swan
#

They're called ephemeral messages by the way

dim cedar
#

mutedrole = discord.utils.get(guild.roles, name = "Muted")

#

in this line of code

#

can i get the specifiq role with the role colour?

past ermine
#

how do oauth code grants work?

queen dagger
#

TypeError: 'coroutine' object is not subscriptable how do you fix this?

#
current_gamerscore = response.json()['profileUsers'][0]['settings'][0]['value']```
#

comes up here and im using aiohttp

tough wagon
#

Info.pypy from Help import Help ... def __init__(self, bot): self.bot = bot bot.help_command = Help(bot) bot.help_command.cog = self ...Help.pypy ... def __init__(self, bot): super().__init__( command_attrs={ 'cooldown': CooldownMapping.from_cooldown(1, 3, BucketType.member), 'description': 'Shows help about the bot, a command, or a category', } ) self.bot = bot ...ErrorFile "/usr/lib/python3.9/asyncio/base_events.py", line 677, in is_closed return self._closed AttributeError: '_UnixSelectorEventLoop' object has no attribute '_closed'

waxen granite
#

how do i send msg in ctx channel for discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

valid perch
#

Give your bot perms to send stuff

waxen granite
#

i mean when this is the case

#

i want to send that i dont have permission

valid perch
#

You dont, you need to either print it or send it somewhere/to someone with perms

#

except CommandInvokeError

slate swan
#

use

#

what

#

why doesn't on_command_error show up in !d

#

oh wait got it

valid perch
#

Likely under ext's

slate swan
#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.
slate swan
#

check if it's a discord.Forbidden

#

if yes, send something in ctx

kindred zinc
#

I am getting a error in this code saying that guild has no attribute 'id'. What am I doing wrong? I am using motor to access mongodb

@commands.Cog.listener()
    async def on_guild_join(self, guild):
        new_guild = {
            'guild_id': guild.id,
            'guild_name': guild.name,
            'prefix': default_prefix,
            'Ranking_System': True
        }
        await config.insert_one(new_guild)

The config object:

mongo_client_id = os.environ['mongo_client_id']
cluster = motor_asyncio.AsyncIOMotorClient(mongo_client_id)
config = cluster['discord']['guild-settings']
default_prefix = '.'
slate swan
#

guild is an str in your case

#

try typehinting to discord.Guild

#

which would accept an id as the parameter

stark bobcat
#

Does roles have an attribute mention?

slate swan
#

or use discord.ext.commands.Bot.get_guild

slate swan
kindred zinc
slate swan
#

which would just be
self.bot.get_guild(id)

stark bobcat
#

Gives a error

slate swan
#

why do you ask if a role has the attribute

#

while using a list

#

are those roles in that list?

#

Make sure you loop through the elements in your list

edgy meadow
#

Hey, does anyone know why this on_member_join function isnt running when someone joins?

@client.event
async def on_member_join(member):
    print("test")
slate swan
#

or just iterate it

#
[object.attribute for object in list]```
edgy meadow
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

lemme

#

lol this 😂

stark bobcat
pliant nacelle
#

why ping code doesn't work ?

slate swan
slate swan
#

a list isn't gonna be a role object, just because there are roles in it

kindred zinc
slate swan
#

nice

stark bobcat
fair axle
#

can you mix slash commands with buttons? for example /button and it responds with here is your button

@ me in response

slate swan
stark bobcat
fair axle
stark bobcat
#

Ok thanks

slate swan
fair axle
#

ok ima go try something

pliant nacelle
jade jolt
#

error?

pliant nacelle
#

yes

jade jolt
#

show

slate swan
#

wrong indents obviously , if its not discord

jade jolt
#

yea

#

i know that, just making sure

slate swan
#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

@pliant nacelle

jade jolt
#

how long can a command prefix be?

slate swan
#

I'm not saying you can't learn discord.py without python knowledge

#

but it's definitely the hard way

pliant nacelle
jade jolt
#

dude

pliant nacelle
#

token 🤣

slate swan
#

then it's just discord and I hate it

#

why are you making screenshots with your phone

jade jolt
#

its not the entire token i see

slate swan
slate swan
jade jolt
#

its capitalised

pliant nacelle
#

so what's the solution

pliant nacelle
#

and bad english two xD

slate swan
pliant nacelle
#

thanks bro is working @slate swan

#

first time i do ping its dosen't working and i changed p to capital P

slate swan