#discord-bots

1 messages · Page 485 of 1

slate swan
#

and it's not getting logged in a file, probably

pliant gulch
#

Ok, so you just invalidated your own point about .env files

slate swan
#

i make my token an import like

token = input("token: ")
hasty iron
#

that seems annoying

slate swan
#

nah its not that bad

pliant gulch
#

Seen a lot of selfbots do that

slate swan
#

i always have the dev page open anyway

#

I made my token like
bot.run("literally my token")

slate swan
pliant gulch
reef shell
#

xd

slate swan
#

i could report so many of my friends for selbotting

#

but they will get caught eventually so

#

tell them to stop

hasty iron
#

partner in crime i see

slate swan
#

they only use it for like fun commands

reef shell
#

eh?

slate swan
#

and activity

#

I hate self-bots

#

even though you can set your own 😹

#

they spam me and I can't reply

pliant gulch
#

inb4 person accesses some random endpoint and gets their discord account terminated

reef shell
#

Changing role colour and activity every miliseconds🗿

reef shell
#

Ik

#

But they try

slate swan
#

immediate block

pliant gulch
#

Discord has said specifically no rainbow roles

slate swan
#

bro its so annoying because i used to nuke WHICH I AM NOT PROUD OF AT ALL AND DO NOT DO IT MY FRIEND GOT ME INTO IT AND ITS HOW I GOT INTO CODING but and now when i make a new account it gets phone locked and stuff, its mad annoying

#

kekw

reef shell
#

🤣

slate swan
#

that's karma at maximum

pliant gulch
#

should've used your brain

hasty iron
#

(if you have one)

slate swan
#

it used to be so fun, then once i kept getting termed i realized it wasnt worth it now i cant even buy nitro 😹

reef shell
#

What's the point tho

hasty iron
#

yeah, feels bad not wasting 5$ on discord cool stuff

slate swan
#

and epic games just throws it to millions of people in 3 days

reef shell
#

Ok we should not discuss bout this

slate swan
#

tru

slate swan
#

lol

reef shell
#

I've seen a server got nuked by some random normal members

#

Without any role

slate swan
#

can't imagine how many times you broke the ToS

#

it's crazy ever since i stopped you guys have actually helped me a lot and made coding fun

#

and you're still here

slate swan
#

but i don't break it anymore so

#

the most i've done was log into my friends acc with his token 😹😹

hasty iron
#

"i was doing crime and i am not doing it anymore therefore i am innocent"

slate swan
#

he's still in jail

#

can't make a new account or buy nitro

reef shell
#

.gg

slate swan
#

well deserved lol

#

i was gonna try and become a discord staff but i know that would be 99% impossible because of what ive done

hasty iron
#

LOL

reef shell
#

DiScOrD sTaFF

#

🗿

slate swan
#

I think-
I think that chance is a bit more than that

hasty iron
#

i dont see why you’re trying to decompile a pyc file too

slate swan
#

is that even python

pliant gulch
#

Wouldn't a decompiled pyc file be just the regular py file

slate swan
reef shell
#

Marshal data is something I've never heard

slate swan
#

do you guys ever go to the dpy server and help?

#

or are there already enough people

hasty iron
#

no

slate swan
#

im banned cuz i wouldnt change my bots prefix 😹

hasty iron
#

bot prefixes can be annoying though there

slate swan
#

bro what

hasty iron
#

you’re trying to test your bot and 50 million random bots appear

slate swan
#

oh lol

#

I never go there

#

rs i told them i had a cmd to change it and that danny could change it if he wanted to

#

but they didnt care

#

I always wonder why everyone's an asshole there

hasty iron
#

you probably did something more

#

that’s not true though

reef shell
hasty iron
#

they’re assholes to people who pretend to know what they’re talking about aka skids

slate swan
#

i didnt have permissions

#

at the time i didnt know that i could make a cmd work for a certain id

icy seal
#

Is using a local filesystem (JSON format) appropriate for a small-scale client?

hasty iron
#

if you want something file based use sqlite

#

its a database

#

and it’s fairly lightweight

icy seal
#

I am going to come across as a bit inexperienced here, so apologies in advance, but could I ask the advantages of a database on a small-scale? I should really learn them at some point... I'm really procrastinating it, but I don't fully understand their uses

#

From what I know files are dangerous to work with in case it might be accessed from multiple points... or maybe speed? But I know very little about the details

#

(Regardless though thank you for the suggestion and I will check it out)

soft trout
#

I dont understand what TypeError: 'int' object is not iterable is.

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

Error:

Ignoring exception in command leaderboard:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 381, in leaderboard
    newlvl=sorted(lvl)
TypeError: 'int' object is not iterable

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

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: TypeError: 'int' object is not iterable
slate swan
#

after in, you should put something iterable

#

for example a list or an array

icy seal
#

oh it's not that actually

slate swan
#

report['users']
returned you a single int

soft trout
#

not really

icy seal
#

you attempt to use newlvl=sorted(lvl)

#

lvl needs to be an iterable for this to work

slate swan
#

oh lol

soft trout
slate swan
#

should've been more careful

soft trout
#

3
8
0
2
0
0
0
7

#

it gave me that

icy seal
#

eh i wouldve made the same mistake DiaPikachu

#

turtlecow try printing the type

slate swan
#

is that a string?

#

should've given like
[3, 8, 0]...

soft trout
#

well it is a string then...

slate swan
#

bruh it's too late for me

icy seal
#

it's most likely a string with numbers split by newlines

slate swan
#

it literally said int

#

I'm gonna go sleep

icy seal
#

oh ur right

soft trout
#

How do I make them a int

icy seal
#

I need more info about your variable lvl

#

debug it with print(type(lvl), repr(lvl))

#

should be enough

soft trout
#
<class 'int'> 3
<class 'int'> 8
<class 'int'> 0
<class 'int'> 2
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
<class 'int'> 7
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
<class 'int'> 2
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
<class 'int'> 0
#

gave me that

soft trout
icy seal
#

oh that's multiple print statements then

#

i think your issue is how you're thinking about this

#

when you do leaderboard, it's called multiple times with only a single lvl variable

#

as you see there, each time a <class 'int'> number is printed, that's bc leaderboard has been called, and that's lvl

#

when you do sorted(lvl), you're sorting a single number

soft trout
#

How would i sort all of them

icy seal
#

which to python obviously makes no sense, int is not iterable

#

well you'd need to store all of the levels

#

so that you have a variable which contains something you can actually sort

#

which has all the data you want

#
newlvl = sorted(u['level'] for u in report['users'])
print(newlvl)
>>> [0,0,0,0,1,2,3,7,8]
#

i was mistaken - the issue is probably because you're iterating over a single item but treating it as the entire list

soft trout
#

how would you reverse the list

icy seal
#

reversed(list_object)

soft trout
#

newlvl = sorted(u['level'] for u in report['users'], reversed=True)

icy seal
#

that would, although the keyword argument is reverse, not reversed

soft trout
#

yeah

#

well i did that and it says Generator expression must be parenthesized

icy seal
#

really? actually that's weird. regardless:
sorted([u['level'] for u in report['users']])

#

wrap it in square brackets. (regarding the error, i thought you could forego parentheses for generator expression if it was inside a function's parentheses)

soft trout
#

thanks

icy seal
#

actually, could i ask what version you're using?

soft trout
#

lemme check

#

3.8.10

icy seal
#

interesting, ty

light radish
#

Hey guys, what is the best choice? Pycord or Nextcord?

lyric moat
#

i tried this to show user activity no error but would not respond

@client.command
async def status(ctx):
  await ctx.send(ctx.author.activities[0].name)```
lament salmon
#

what is ctx?

icy seal
#

it’s a context object which i believe is defined in discord.ext.commands

lament salmon
#

oh ok

icy seal
#

also @lyric moat try printing it out to the console

icy seal
#

i would look through the documentation to see why your code isn’t working but honestly it’s just faster to have you debug it lol

lyric moat
icy seal
#

wdym it gave you something to import?

#

what was the output when you printed it?

lyric moat
#

this

#
from discord import Member
icy seal
#

what is mins supposed to be

#

@lyric moat could you print the output from the console? discord.Member is just a standard object type in the discord library, idk what u mean by it gave you it to import

tulip oracle
#

that is basic python, you are calling a var that isnt defined yet

#

like getting something out of thin air

#

no error or nothing called the your check isnt being called

#

i dont really understand this

#

@ everyone role is in every channel

#

by not checking for that?

#

well like i said

#

its a weird check

somber musk
#

how can i use from discord.ext import commands

valid niche
#

General discord API question. Directly interfacing with the gateway API yields me a HELLO on connect, when i send back HEARTBEAT and then IDENTIFY, the next message i get from the gateway is a CLOSE with code 1002. I have been told it's because the payloads for what i sent are wrong, but idk what exactly is wrong.

communication

{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250,"_trace":["[\"gateway-prd-main-1bw8\",{\"micros\":0.0}]"]}}
sent identify
WSMessage(type=<WSMsgType.CLOSE: 8>, data=1002, extra='')

HEARTBEAT

    async def heartbeat(self):
        """Send HB packet"""
        payload = {
            'op': self.HEARTBEAT,
            'd': self.sequence,
            'compress': True,
            }
        await self.socket.send_json(payload, compress=9)

IDENTIFY

    async def identify(self):
        """Sends the IDENTIFY packet"""
        print("sent identify")
        payload = {
            'op': self.IDENTIFY,
            'd': {
                'token': self.token,
                'properties': {
                    '$os': sys.platform,
                    '$browser': 'disthon.',
                    '$device': 'disthon',
                },
                'compress': True,
            }
        }
        await self.socket.send_json(payload, compress=9)
slate swan
#

whats the difference of discord.Bot and commands.Bot?

valid niche
valid niche
#

not sure where you found that

#

but that doesn't exist

slate swan
#

oh

valid niche
#

or wait

#

unless the slashcommands library named it Bot

#

for odd reasons

honest wing
#
@bot.command()
async def banner(ctx, user: discord.User=None):
    await ctx.message.delete()
    if user == None:
        r = requests.get(f"https://discord.com/api/v9/users/{bot.user.id}", headers={"Authorization": "Bot " + TOKEN}).json()
        if r["banner"] == None:
            embed = discord.Embed(description=f"You don't have a banner.", color=0x2f3136)
            embed.set_footer(text=footer)
            embed.set_author(name=f"{ctx.author} ({ctx.author.id})")
            await ctx.send(embed=embed)
        else:
            embed=discord.Embed(description=f"Here is, **your**'s banner.\n\n[png](https://cdn.discordapp.com/banners/{ctx.author.id}/{r['banner']}.png)\n[jpg](https://cdn.discordapp.com/banners/{ctx.author.id}/{r['banner']}.jpg)\n[gif](https://cdn.discordapp.com/banners/{ctx.author.id}/{r['banner']}.gif)\n",color=0x2f3136)
            embed.set_footer(text=footer)
            embed.set_author(name=f"{ctx.author} ({ctx.author.id})", icon_url=str(ctx.author.avatar_url))
            embed.set_image(url=f"https://cdn.discordapp.com/banners/{ctx.author.id}/{r['banner']}.gif?size=4096")
            await ctx.send(embed=embed)```

Always says you don't have a banner even if you have one, and I have no clue what to do lol
valid niche
honest wing
valid niche
#

that...does not matter

honest wing
#

.banner doesn't work below 2

valid niche
#

requests in dpy have always been a bad thing since the start of the library

slate swan
#

But why

valid niche
#

because async

#

blocking

#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

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

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

honest wing
#

i know about async blocking

slate swan
#

I didn't know they block async

honest wing
#

i don't feel like not using requests

valid niche
#

aiohttp is async and doesn't block

#

easy as that

slate swan
#

Fair

#

So use aiohttp instead

tulip oracle
#

how can i use await commands.MemberConverter.convert() accurately? i see no description in the docs of supplying the id= or name=, so if i add (ctx,argument) it asks for the argument? confused

valid niche
#

and strange, you should print out the request and see what it all contains

valid niche
#

there now you used the converter

tulip oracle
honest wing
#

it just contains the banner, i had it working on a mention, just not self.

tulip oracle
#

purposefully

valid niche
# tulip oracle yeah i cant use typehint converter for this module

i mean you're adding yourself a lot more hassle...for what seems no reason,

Anyways you get the on_message, which gets processed by the bot internally, or in an on_message event using process_commands

This gets the context, and invokes it. ctx.invoke is a shortcut (with extra stuff) for ctx.command.invoke so it goes there

This invoke call calls prepare on the ctx. Prepare does the last bits and things like parse the arguments. This can be found here: https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ext/commands/core.py#L816

Parsing the arguments is done here: https://github.com/Rapptz/discord.py/blob/45d498c1b76deaf3b394d17ccf56112fa691d160/discord/ext/commands/core.py#L700
This part runs the converters.

unkempt canyonBOT
#

discord/ext/commands/core.py line 816

await self._parse_arguments(ctx)```
`discord/ext/commands/core.py` line 700
```py
async def _parse_arguments(self, ctx: Context) -> None:```
valid niche
#

from there it should be fine i guess

#

you should be able to figure it out

tulip oracle
#

haha

#

need a different method to ban a user in the same command, and adapt to the user being in the server and not

valid niche
#

and do guild.ban(user)

#

works for both members in and out of the guild

#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
tulip oracle
#

i see, thank you

zenith hare
#

a few days ago I asked for help with this problem, someone told me to try enabling the attempts, but the same problem is still happening

valid niche
#

intents is a requirement for this caching, and for the rest it's just.....whatever happens

slate phoenix
#

or remove await

jade jolt
#

fetch_channel uses the API, get_channel is from cache iirc

slate phoenix
#

yep

jade jolt
#

just a better idea to use get_channel whenever you can

jade jolt
#

only noticed that just now

slate phoenix
#

oh yea i didnt notice that either

zenith hare
#

noted, thanks guys

woeful fable
#

hi, just wondering if its possible for me to write some code inside main.py and have it trigger learn and generate to run

jade jolt
#

thats possible.

woeful fable
#

specifically im trying to make on_message inside main.py pass the message content for the learn.py to write into the dictionary

jade jolt
#

sorta

woeful fable
#

meaning every message triggers the learn app to learn it

jade jolt
#

uhhh yeah thats possible

woeful fable
#

may i ask how?

jade jolt
#

let me make an example brb

honest wing
#
    permissions = ch.permissions_for(ctx.author)
AttributeError: 'Object' object has no attribute 'permissions_for'```
#

what is this error

slate phoenix
#

ck.permissions_for doesnt exist

honest wing
#

i have no ch variable lmfao

wicked atlas
#

Can you send your code?

slate phoenix
#

post your full code

honest wing
#
@bot.command()
@commands.has_permissions(administrator = True)
async def setprefix(ctx, new_prefix):
    await bot.db.execute('UPDATE guilds SET prefix = $1 WHERE "guild_id" = $2', new_prefix, ctx.guild.id)
    embed = discord.Embed(description=f"Prefix has been updated to {new_prefix}", color=0x2f3136)
    embed.set_footer(text=footer)
    await ctx.send(embed=embed)```
#

Error happens with that command

whole plinth
#

I would like to verify members by sending a code to their mailbox (of our organization) and let them send it back to the bot. To verify that they are from the organization...
Is there something like this?

wicked atlas
honest wing
#

I'll check

honest wing
wicked atlas
#

Where are you running this command from?

honest wing
#

Wdym?

wicked atlas
#

This is a discord bot command. Where are you running the command

honest wing
#

In my server

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

honest wing
#
  File "main.py", line 59, in setprefix
    async def setprefix(ctx, new_prefix):
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\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: AttributeError: 'NoneType' object has no attribute 'id'```

There's that if that helps lol
wicked atlas
#

I'm just a bit confused as to why ctx.guild is None

river walrus
wicked atlas
#

They say they're doing it in their server

river walrus
#

Oh

#

Hmmm

wicked atlas
#

@honest wing Can you print out the type of ctx?

print(type(ctx))
vague fable
#

Guys how can I add a space in a discord def

#

Or at least imitate the function

wicked atlas
#

def?

vague fable
#

like if I want to make a function _Example example

vague fable
wicked atlas
#

You can't have spaces in function names

vague fable
#

Or how can I like

#

async Example():
example = blahblah

wicked atlas
#

before the first line

honest wing
#

ok

wicked atlas
#

with your DB stuff

wicked atlas
honest wing
#
Traceback (most recent call last):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 943, in on_message
    await self.process_commands(message)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 940, in process_commands
    await self.invoke(ctx)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 851, in invoke
    await self.prepare(ctx)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 778, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1076, in can_run
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 338, in async_all
    for elem in gen:
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1076, in <genexpr>
    return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
  File "C:\Users\misery\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1762, in predicate
    permissions = ch.permissions_for(ctx.author)
AttributeError: 'Object' object has no attribute 'permissions_for'```
vague fable
#

let me get a help channel

wicked atlas
#

What version of dpy do you have?

honest wing
#

ill check 1 sec

#

is it
import discord
print(discord.version)

wicked atlas
#

I think it's ```py
discord.version

honest wing
#

i totally forgot ngl

#

1.5.0

wicked atlas
#

Ah, so you're using an older version

#

Install the newest release

honest wing
#

the command was working earlier though, idk what happened

slate swan
#

1.4.2 > all

honest wing
slate swan
honest wing
#
intents = discord.Intents(messages=True, members=True)
member_cache_flags = discord.MemberCacheFlags.none()```

```py
intents=intents, member_cache_flags=member_cache_flags```
#

was messing it up for some reason, thank you guys tho

rugged tinsel
#

how do you make a command cooldown for every 5 seconds?

slate swan
#

i believe it's
@commands.cooldown(1,5 BucketType.user)

#

@rugged tinsel

#

i could be wrong

rugged tinsel
#

ok

#

ill try it out

#

it should be above client command?

final iron
rugged tinsel
final iron
rugged tinsel
final iron
#

Also you should of sent the documentation

vague fable
slate swan
final iron
slate swan
#

hm

lofty heron
#

hi, how can i make my bot create an invite for the guilds it is in? i have the guild ids

empty raven
#

I got banned for using a python bot 😟

surreal creek
lyric moat
#

how can i make server banner command?

surreal creek
lyric moat
young acorn
#

You guys know of a way to have the bot periodically execute a subroutine?

empty raven
#

@surreal creek I made a bot through python and it was flagged saying it was a self bot 🥺

surreal creek
lyric moat
surreal creek
surreal creek
empty raven
#

Ya my main account got disabled does anyone know or if my account will be undisabled

#

I put in a claim

surreal creek
#

idk

surreal creek
empty raven
#

Welp rip my nitro 😭

young acorn
surreal creek
#
import asynciot#The only thing u need to import 
async def forever():
  print('Task Complete')
  asyncio.sleep(15)

  

bot.loop.create_task(forever())
surreal creek
#

hope it works 🙂

young acorn
#

Ah okay, you can create a task with the bot

lyric moat
#

error why it sends 2 times?

final iron
surreal creek
young acorn
lyric moat
# lyric moat
@client.command()
async def banner(ctx):

    if not ctx.guild.banner:
        embed = discord.Embed(title="Server has no banner!", color=0xf7fcfd)
        return await ctx.send(embed=embed)

    else:
        embed = discord.Embed(title=f"Banner of {ctx.guild.name}", color=0xf7fcfd)
        embed.set_image(url=ctx.guild.banner_url_as(format='png'))
        await ctx.send(embed=embed)

    await ctx.send(embed=embed)```
lyric moat
#

btw how i make it the same size as the banner?

surreal creek
#
@client.command()
async def banner(ctx):

    if not ctx.guild.banner:
        embed = discord.Embed(title="Server has no banner!", color=0xf7fcfd)
        return await ctx.send(embed=embed)

    else:
        embed = discord.Embed(title=f"Banner of {ctx.guild.name}", color=0xf7fcfd)
        embed.set_image(url=ctx.guild.banner_url_as(format='png'))
        await ctx.send(embed=embed)#THIS IS FIRST TIME

    await ctx.send(embed=embed) #THIS IS SECOND TIME
surreal creek
surreal creek
lyric moat
#

still sends 2 times

surreal creek
lofty heron
#

well tenks dodged a bullet

surreal creek
#

in the last line

lyric moat
#

thanks

surreal creek
maiden fable
waxen monolith
#

The first @commands.command() works, but the second one throws an error, is there a reason for this? I'm not sure what's going on here

young acorn
waxen monolith
#

AttributeError: 'Command' object has no attribute 'command'

lament mesa
#

oh, do you have a command named commands?, rename it

waxen monolith
#

Ah, I have a 'commands' command

#

that's probably the issue

lament mesa
surreal creek
waxen monolith
#

weird, the bot still isn't detecting commands

young acorn
waxen monolith
#

oh I have client.command not client.add_command

surreal creek
waxen monolith
#

okay changing that doesn't work

young acorn
waxen monolith
#

So, I'm using @commands.command(), does that not work with client.add_command()? At the start I do have client = commands.Bot(command_prefix='?')

surreal creek
waxen monolith
#

When I did everything in client.on_message(message) it worked (but that's a pretty bad solution), but this isn't working, I haven't really used discord.ext before though

surreal creek
waxen monolith
#

Do I keep the @young torrentmands.command()?

#

sorry for the ping whoever that was

waxen monolith
#

@young torrentmands.command()

surreal creek
#

tf

waxen monolith
#

oh sorry l'pain

#

no idea why it's changing to that

#

their username is com

surreal creek
surreal creek
waxen monolith
#

@commands.command()

surreal creek
waxen monolith
#

ah, I tried that

surreal creek
surreal creek
valid perch
unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
waxen monolith
#

actually let me repaste that to censor something

#

@surreal creek

boreal ravine
waxen monolith
boreal ravine
waxen monolith
#

Weird, commenting out all the code except for that works, but all the code doesn't work

boreal ravine
#

make an error handler so you know whats the error lol

waxen monolith
#

apparently the issue was my on_message code

surreal creek
wicked atlas
worthy wagon
#

Is this correct?

wicked atlas
#

Does it work?

slate swan
#

Should work

worthy wagon
#

says bad request, unknown emoji, but the emoji does exist, I might have the emoji ID wrong, but I don't know how to return an emoji id

#

rgbchair is the emote

#

I thought you just right click and press copy id

slate swan
#

no ,

worthy wagon
#

mb

slate swan
#

You need to use :emoji:

worthy wagon
#

?

slate swan
#

to get the elapsed name

#

\:emoji:

worthy wagon
#

oh

wicked atlas
#

Isn't that what they have though...

slate swan
#

you won't get the id by right clicking on it

#

It may be the message id most probably

wicked atlas
#

You can get the ID by right clicking on it

tulip oracle
#

wanting to catch when someone posts a link, and the link does not embed
i used
if len(message.embeds) == 0:
but it wouldnt catch it,

slate swan
wicked atlas
worthy wagon
#

It's working now.

wicked atlas
#

hmmm

worthy wagon
#

I appreciate the help guys!

slate swan
#

¯\_(ツ)_/¯

wicked atlas
#

strange, used to work for me

worthy wagon
#

\:emojiname:

slate swan
ocean leaf
#

is there any way to play audio files in discord without using ffmpeg? bcoz i am using replit :(

wicked atlas
#

So anyway, @worthy wagon if that isn't working for you, you may need to get the emoji object and pass that instead

slate swan
ocean leaf
slate swan
#

and you can use it if you want to play some locally stored files

ocean leaf
#

how

#

any vdeo?

#

any tutorial?

wicked atlas
#

I feel like saying that ffmpeg "works" is a bit weird, since replits filesystems are ephemeral

#

I don't even know how you would really install it

slate swan
#

you can find couple of docs related to it

wicked atlas
#

Isn't that just the python bindings?

slate swan
#

yeah , and it configures it to work with ffmpeg

heavy radish
#

Heyy, I've got a question

#

I need help making a custom command and this is how I want it to work. I want to be able to store a users name in it. So the command would start of blank like !channel and the output would be None! Set one now!. Once I set it like !channelset @user I want that to be channel specific. So If i do !channel in another channel, it would say None! Set one now!. However, if I do it in one that has been set, it would give me user output like @user. Any idea on how to do so?

wicked atlas
heavy radish
#

@slate swan ?? Can you help?

wicked atlas
#

Hmm, seems to work, weird that it does that

upbeat vigil
#

hey i made this, and it doesnt work

#

cna anyone tell me what i did wrong

boreal ravine
heavy radish
boreal ravine
#

For the 10th time no

amber pawn
#

can you test for me this script?

#

i write myself

boreal ravine
#

sure

amber pawn
#

i dmed you

dapper cobalt
hollow agate
#
@client.command()
async def transcript(ctx):
    await ctx.message.delete()
    with open("file.txt", "w") as file:
        msg = await ctx.channel.history(oldest_first=True, limit=1).flatten()
        y = msg[0].mentions[0]
        file.write(f"{ctx.channel.name} | {y.name}" + "\n \n \n")
        async for message in ctx.history(limit=None):
            file.write(str(f"[{message.author}]: {message.content}" + "\n"))

    with open("file.txt", "rb") as file:
        await ctx.send("Your file is:", file=discord.File(file, "transcript.txt"))``` How can I make the order of the messages flip so the oldest message is on the top rather than on the bottom?
pulsar stream
#

oldest_first=True. same as the first one

#

on the second history

hollow agate
#

Ahhh, thank you!

pulsar stream
#

but wait

#

why do you even have the first history

hollow agate
#

Ah, that was a place holder for when I got back to it, I thought I needed to use .reverse

vagrant brook
unkempt canyonBOT
vagrant brook
#

🙂

hollow agate
pulsar stream
#

oh okay

upbeat vigil
#

`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: AttributeError: module 'datetime' has no attribute 'now'
 172.18.0.1 - - [21/Sep/2021 04:01:29] "GET / HTTP/1.1" 200 -

boreal ravine
#

Code?

upbeat vigil
pliant gulch
#

You need to do datetime.datetime.now()

boreal ravine
pliant gulch
#

You imported it as import dateteime rather then from datetime import datetime

upbeat vigil
#

so like this?

boreal ravine
#

Yes datetime is the module and datetime and time are the sub modules

upbeat vigil
#

i see

lofty heron
#

hi, how can i check if 2 messages with the same thing have been sent? i have no idea how to do it lol

dapper cobalt
#

Then learn Python.

#

And to get the message's content, it's message.content.

#

!d discord.Message.content

unkempt canyonBOT
lofty heron
#

alright thanks

upbeat vigil
#

tysm huys

#

guys*

#

it worked

ocean leaf
hollow agate
#
        async for message in ctx.history(limit=None, oldest_first=True):
            time = datetime.now(tz=pytz.timezone('America/Tijuana'))
            msgtime = message.created_at.strftime({"%I:%M %p"})
            file.write(str(f"({msgtime}) [{message.author}]: {message.content}" + "\n"))``` How could I set the msgtime time zone to America/Tijuana?
drifting arrow
hollow agate
#

It doesn't because it says it's 4:00 am, but in reality it's 10:00 pm here, plus I can't use my local time xd

drifting arrow
#

Lemme quickly do some googling

drifting arrow
# hollow agate It doesn't because it says it's 4:00 am, but in reality it's 10:00 pm here, plus...
lofty heron
#

hi i'm trying to make my bot send something if a previous id has been seen but it returns with

with open("previousids.txt") as file:
  previousids = [previousids.strip().lower() for previousids in file.readlines()]
  
@client.event
async def on_message(ctx, message):
  if any(previousids in message for previousids in previousids):
    await ctx.send('this id has been seen before. bruh moment')
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'message'
hollow agate
#

Hmmm- not sure how I could use that

slate swan
lofty heron
#

oh.

slate swan
#

message.channel.send

lofty heron
#

hmm ok thanks :D

#

hmm then returns with

Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 63, in on_message
    if any(previousids in message for previousids in previousids):
  File "main.py", line 63, in <genexpr>
    if any(previousids in message for previousids in previousids):
TypeError: argument of type 'Message' is not iterable
slate swan
#

What are you trying do?

lofty heron
#

make the bot send something when a certain word in a txt file is sent

slate swan
#
for word in blacklist:
    if word in message.content:
#

Do something like that

lofty heron
#

hmm ok i'll try

valid galleon
#

So im making a custom prefix command using mongodb, and when i use the setprefix command, it adds the info in the collection, but i also get this error, and the new prefix wont work:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Bot' object is not callable  ```
My code:
```py
@client.command()
async def setprefix(ctx, prefix):
      db = cluster["discord"]
    collection = db["prefixes"]

    guild_id = ctx.guild.id
    server_prefix = prefix

    if(collection.count_documents({})) == 0:

        prefix_info = {'Guild_id': guild_id, 'Prefix': server_prefix}
        collection.insert_one(prefix_info)

    else:
        prefix_info = {'Guild_id': guild_id, 'Prefix': server_prefix}
        collection.update_one({'Guild_id': guild_id}, {'$set': {'Prefix': prefix}})

    await ctx.send(f"My prefix is now {prefix}")

    finding_prefix = collection.find_one({'Prefix': {'$eq': prefix}})

    view_finding_prefix = finding_prefix.values()
    iterate_view = iter(view_finding_prefix)
    first_value = next(iterate_view)

    client(command_prefix = str(first_value), case_insesitive = True)
#

?

#

and this is after the

client = commands.Bot(command_prefix = '!', intents = discord.Intents.all())
```line
valid galleon
#

not before

valid galleon
slate swan
#

Show me full error

valid galleon
#
    ret = await coro(*args, **kwargs)
  File "c:\Users\-----\Desktop\Python\Projects\discord bot\DiscordBot.py", line 46, in setprefix
    client(command_prefix = str(first_value), case_insesitive = True)
TypeError: 'Bot' object is not callable
#

@slate swan

#

would moving the code into a cog fix it?

drifting arrow
#

uhh

slate swan
drifting arrow
#

not really.

valid galleon
#

?

drifting arrow
#

If your code won't work outside of the cog it won't work inside of the cog

slate swan
#

You currently have a prefix set. You create a command in the wrong way that will change the original prefix. This cannot be done this way.

#

If you think more about it you will found why cant do that

#

Specifically you are trying to change the original prefix to something else for all the servers that are your bot, not for each one individually.

valid galleon
#

do you know any way to do it properly?

slate swan
valid galleon
#

i'll try it

slate swan
#

I suggest check this tutorial

valid galleon
#

i'll try rewriting the entire thing once

slate swan
maiden fable
#

Do u know... YouTube videos aren't preferred for dpy

#

^^^

maiden fable
#

Who here can help me make a Paginator which will divide the string if the number of new lines exceeds the number I specify?

fading harness
#

i want to ask my bot to make the invite to my server like choi!mi 25 will make a invites with maximum 25 uses what do I write in the code

maiden fable
unkempt canyonBOT
#

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

Creates an instant invite from a text or voice channel.

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

and how can the bot send it

maiden fable
#

just like u send a simple message bro

#
invite = await channel.create_invite()
await ctx.send(invite)
fading harness
maiden fable
fading harness
#

yes

drifting arrow
#

opinions? left or right for formatting?

maiden fable
maiden fable
#

also adding a color will be better

lofty heron
#

hi, when i run this why does nothing happen when i run t!help?

import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='t!')
TOKEN = os.environ['mrow']
@bot.command
async def stoopid(ctx):
  await ctx.send('no')

@bot.event
async def on_ready():
  print(f"Logged in as {bot.user.name}")
  print("---------------------")

with open('previousids.txt', 'r') as f:
    global ids
    previousids = f.read()
    ids = previousids.split()

@bot.event
async def on_message(message):
  for word in ids:
    if word in message.content:
      await message.channel.send('this id has been seen before')

bot.run(TOKEN)
drifting arrow
lofty heron
#

colour = 0x hex code here without

maiden fable
unkempt canyonBOT
#
Certainly not.

No documentation found for the requested symbol.

maiden fable
#

Bro

#

!d discord.Embed.colour

unkempt canyonBOT
#

The colour code of the embed. Aliased to color as well. This can be set during initialisation.

lofty heron
#

kekw

maiden fable
#

:blobpain:

lofty heron
#

yeah

drifting arrow
#

wow it requires the u?!

maiden fable
#

No

lofty heron
#

no it doesn't

drifting arrow
#

k good

maiden fable
#

read the embed. it can be color also

drifting arrow
#

coz i was aboutta say. I'm australian but even i'm lazy and leave the 'u' out

maiden fable
#

@unkempt canyon was just having a stroke

gusty whale
#

anyone know of any D.py forks that support the new features?

gusty whale
#

hmm

maiden fable
#

🤷‍♂️ I use that and haven't got any problems till now

gusty whale
#

!pypi disnake

unkempt canyonBOT
gusty whale
#

ok thanks!

drifting arrow
#

Unless there's a way to make on_message stop doing its nonsense, dont use it

lofty heron
#

oh hmmso i put the command after othe event

maiden fable
lofty heron
#

ok tenks

maiden fable
#

or u can use bot.listen() instead of bot.event

#

Yea, it works

velvet sinew
#

anyone knows how to add custom emojis in embed discord.py?

#

Dm if u know

lofty heron
#
\:crossed_swords:
maiden fable
#

Yea

lofty heron
#

do something like that

#
\:kubernetes: 
maiden fable
#

the variable name for a constant

drifting arrow
maiden fable
lofty heron
maiden fable
#

Yea

drifting arrow
#

Oh

lofty heron
#

lol it would be cool if i could change the background colour

drifting arrow
#

It would be cool

keen talon
drifting arrow
maiden fable
#

🤣

drifting arrow
#

Easier to just ask questions

maiden fable
#

It is fine. Calm down

cobalt jacinth
#

can i set embed footer text to be a different color

keen talon
keen talon
#
damn
lofty heron
cobalt jacinth
maiden fable
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

maiden fable
lofty heron
#

lol footer no chance

keen talon
maiden fable
river walrus
#

Thanks tho

maiden fable
#

I don't think anyone here (I think) is that genius to contribute to your project (At least idk anything about Python)

lofty heron
#

lol invalid syntax kekw

maiden fable
lofty heron
#

ok

maiden fable
#

root indent

lofty heron
#

mm ok

keen talon
lofty heron
#

uhwaefiy

maiden fable
#

L
0
L

lofty heron
#

mmmmmmmmmmfkawejnibhu

#

mega brein brainmon

keen talon
#

😎

maiden fable
#

Hey @keen talon mind helping me with something if u r free?

keen talon
maiden fable
#

So I am trying to making a Paginator and the paginator should do something like...

There will be a dict, and the key value pairs of the dict will be divded in a group of 10 in case the length is more than 10... So, how can I split the dict key value pairs into groups of 10?

dreamy sluice
#

Is there any exception which checks whether bot is already in a vc upon a request for it to join?

#

sorry if my wording isn't clear 😅

maiden fable
#

!d discord.ClientException

unkempt canyonBOT
#

exception discord.ClientException```
Exception that’s raised when an operation in the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") fails.

These are usually for exceptions that happened due to user input.
maiden fable
keen talon
#

u know numpy ?

maiden fable
#

No

keen talon
#

u can do array.reshape with the keys

drifting arrow
#

Man. setting up all these bot.events is time consuming

dreamy sluice
gusty whale
#

What exactly is the ui type feature called?
like its a message which you can click different buttons and things on

keen talon
maiden fable
maiden fable
gusty whale
gusty whale
keen talon
lofty heron
#

umm 👀

spring flax
lofty heron
#

:dies:

#

i usually use @client.command but tiwaeou

#

aaa the pain

velvet sinew
#

Help pls

#

How to add custom emojis

#

In embed

drifting arrow
#

Can someone tell me what a group channel is? is that what discord refers to as a thread?

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.

hot cobalt
#

@slate swan You have a URL shortener in your code

#

The filters get triggered

hot cobalt
drifting arrow
#

issue?

#

you aren't use an f string

#

r=requests.get(" should be r=requests.get(f"

#

dw

#

I take forever to code coz I keep forgetting to do silly things like that

velvet sinew
#

Not working

#

How to add emojis in embed pls tell

#

I'm trying

#

But not working

#

Ok

#
embed.add_field(name= " <emoji_4 889758662640422922> FUN COMMANDS", value= " 8ball, slap, hentai, boobs, neko, pussy, anal, blowjob, lewdneko" )
#

Share the correct code

#

Okk

river walrus
#

That's the spirit

lofty heron
#

hi does anybody know how to only get the first few characters of something a user says?

crisp drift
#

hey uh, how do i send output of my terminal?
i tried this code but it sends 0 when i type sqd-t echo f
i use linux,

msg = message.content
reply = message.reply
sendmsg = message.channel.send
if msg.startswith('sqd-t '):
   cmd = msg.split('sqd-terminal ', 1)[1]
   print('')
   print(msg)
   print('Command requested: ' + cmd)
   await reply('**Sending command to terminal...** `' + cmd + '`')
   cmd = str(cmd)
   await sendmsg('`Output:`\n\`\`\`' + str(os.system(cmd)) + '\`\`\`')

why does it do that?

#

ping on reply

slate nymph
#

any free web servers for bot?

gloomy coral
#

sry for saying so

slate nymph
#

please tell me

gloomy coral
lofty heron
#

replit

lofty heron
slate nymph
#

replit works for only 1 hour

gloomy coral
#

u can ping it with uptimerrobot

#

it wld work well for me

velvet sinew
#
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
#

Help pls

slate nymph
#

okay

gloomy coral
gloomy coral
stone palm
#

how do i get the authors voice channel?

#

ctx.author.voice.channel?

boreal ravine
icy seal
#

i believe so, Invisible

lofty heron
velvet sinew
ionic wadi
#

discord.ext.commands.errors.ExtensionNotFound: Extension 'Moderation' could not be loaded.

What does this mean, something wrong In the main loading code or in the extension code?

spring flax
#

the cog does not exist.

ionic wadi
#

Same error

#

Yes

spring flax
#

for cogs, it is @commands.command

ionic wadi
#

prefixes = "", "c!", "C!"
bot = commands.Bot(command_prefix=prefixes)

Basically this right?

#

This Is what I have now, still the error.

spring flax
#

prefixes=["first", "second", "third"]

ionic wadi
#

Np

spring flax
#

you should be focusing on that then lol

ionic wadi
#

Oh wait, I am stoepid.

#

It says theres something wrong in the main script

#

File "/home/container/bot.py", line 16, in <module>
bot.load_extension("Moderation")

#

Traceback (most recent call last):
File "/home/container/bot.py", line 16, in <module>
bot.load_extension("Moderation")
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 676, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'Moderation' could not be loaded.

#

I somehow recognize that 😂

coral ermine
#

how do i make the bot send a "this message is only visible to you" message

ionic wadi
#

Oh I fixed It, moderation instead of Moderation but Now i get some sketchy error

coral ermine
boreal ravine
coral ermine
#

ohh

slate swan
#

how can i create a dashboard for my bot any resource

ionic wadi
boreal ravine
#

Like this you mean? @coral ermine

ionic wadi
#

File "/home/container/moderation.py", line 11, in Moderation
@commands.event
AttributeError: module 'discord.ext.commands' has no attribute 'event'

slate swan
boreal ravine
unkempt canyonBOT
#

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

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

how can i run that app

boreal ravine
coral ermine
ionic wadi
#

@commands.Cog.listener()
async def on_ready():
channel = bot.get_channel(848262509244055622)
await channel.send("Moderatie Cog Ingeladen")
print("Moderatie Cog Ingeladen")

TypeError: on_ready() takes 0 positional arguments but 1 was given

ionic wadi
slate swan
#

not user data

#

is there any way just to get bot data

#

?

visual island
slate swan
visual island
#

bot data?

#

bot.user?

slate swan
#

nah

#

see i want to create a dashboard

#

but there a problem my bot is deployed on heroku so how can i run

#

flask or quart

#

with it

#
        today = datetime.utcnow().strftime("%Y%m%d")


    @commands.Cog.listener()
    async def run_once_when_ready():
        with open('daily_poll.txt','r') as file:
            if today in daily_poll:
                print(today)
            else:
                print("Cant find it wot?")

Hey this is my code, The bot isnt printing anything nor is there any error thinkcat

#

@slate swan insert today with in the function

#

before file handler

cinder echo
#

I want to change the binary data from DB to jpg and send it to the user. Is there a way to send an image without saving it?

bitter depot
#

Really you need to store the image if you want to guarantee the image will always be sent

slate swan
#

! help

#

!hepp

#

How to host discord bot?

#

Use money and free

river walrus
spring flax
#

@slate swan
If you need to run your bot 24/7 (with no downtime), you should consider using a virtual private server (VPS).
This is a list of VPS services that are sufficient for running Discord bots.

https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.

There are no reliable free options for VPS hosting. If you would rather not pay for a hosting service, you can consider self-hosting. Any modern hardware should be sufficient for running a bot. An old computer with a few GB of ram could be suitable, or a Raspberry Pi (any model, except perhaps one of the particularly less powerful ones).

slate swan
#
    self.bot.loop.create_task(run_once_when_ready())
NameError: name 'self' is not defined

Wondering why I am getting this error?

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

I have defined it in my init also

drifting arrow
#

@slate swan i assume "create_task" is a function correct? if so, you need self before run_once_when_ready()

#

it's what i'd try anyway

#

Give it a shot and if it doesn't work then I'm all outta ideas

slate swan
#
    async def run_once_when_ready():
        await bot.wait_until_ready()
        today = datetime.utcnow().strftime("%Y%m%d")
        with open('daily_poll.txt','r') as file:
            if today in daily_poll:
                print(today)
            else:
                print("Cant find it wot?")
    self.bot.loop.create_task(run_once_when_ready())

Thats the code so you mean async def self.run_once_when_ready():?

drifting arrow
#

Oh

#

Oh

#

there's your issue.

async def run_once_when_ready():
needs to be
async def run_once_when_ready(self):
drifting arrow
#

soz I pressed enter

grand anvil
drifting arrow
#

IDK THERE NEEDS TO BE A SELF SOMEWHERE AAHH

slate swan
#

Oh okay thanks both of you! Lemme try that

drifting arrow
#

My process is normally to add self everywhere until it works. i'm going back to being a derp.

lofty heron
#

hi i'm not sure why the below code has an output of the image. can somebody help?

@bot.command()
async def idlist(ctx):
  lol = open('previousids.txt', 'r')
  embed=discord.Embed(
    title='id only log',
    description=(lol),
    colour=ctx.message.author.colour
  )
  await ctx.send(embed=embed)
  kekw = open('reasons.txt', 'r')
  embed=discord.Embed(
    title='id and reason log',
    description=(kekw),
    colour=ctx.message.author.colour
  )
  await ctx.send(embed=embed)
drifting arrow
#

@lofty heron i think it's coz you need to parse your lol into a string.

#

I say think coz like with @slate swan i'm taking a stab and guessing here. and that's where i'd start.

drifting arrow
#

no?

#

Damn. well that's me outta ideas.

grand anvil
#

that'll just print a "lol" in his embed

drifting arrow
#

No what I meant was.
lol doesnt have string items in it. he needs to parse the contents of it into a string.

grand anvil
#

oh

drifting arrow
#

Sorta like reading a json file. Sure you can open it up and pray to god it works right then. or you can process it into the parts you need/want and in a way you can read it

lofty heron
#

tenks

drifting arrow
#

Although a json file isnt the best example since it's basically a list/dict

grand anvil
lofty heron
#

hmm

#

um do i just leave the bracket after readline blank?

#

for all lines

grand anvil
drifting arrow
#

try

    description=(lol.read),
lofty heron
#

ok i'll try

grand anvil
lofty heron
#

yeah that

grand anvil
#

yea leave it blank if you wanna read a single line

drifting arrow
#

wait i forgot the ()

description=(lol.read())
grand anvil
#

if you want to read all lines, use lol.readlines() but it will give you a list of lines

drifting arrow
#

🤞 lets hope w3schools do us a solid for a change and has correct code

lofty heron
#

kekw

drifting arrow
#

otherwise im off to stackoverflow

grand anvil
#

if you wanna print a list of lines, just use "\n".join(whatever you named the list)

#

@lofty heron are you trying to read a single line or multiple lines?

lofty heron
drifting arrow
#

Are you storing and updating everything in a .txt file? why not use a database? or json file?

heavy folio
#

hi tram

lofty heron
#

idk how to use anything else

heavy folio
lofty heron
#

oh hey

drifting arrow
#

I commend you for making your database txt files. Perfectness. But if we're being smart, use json or database

grand anvil
# lofty heron multiple

do this:

@bot.command()
async def idlist(ctx):
  lol = open('previousids.txt', 'r')
  lines = lol.readlines()
  lines = "\n".join(lines)
  embed=discord.Embed(
    title='id only log',
    description=lines,
    colour=ctx.message.author.colour
  )
  await ctx.send(embed=embed)
  kekw = open('reasons.txt', 'r')
  lines = kekw.readlines()
  lines = "\n".join(lines)
  embed=discord.Embed(
    title='id and reason log',
    description=lines,
    colour=ctx.message.author.colour
  )
  await ctx.send(embed=embed)```
lofty heron
heavy folio
#

ohh

drifting arrow
heavy folio
#

oh

lofty heron
#

ty :D it works stonks

grand anvil
#

👍

#

glad I could be help :)

drifting arrow
#

Since there's some smart people here. Can someone help me?

    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        channel = self.client.get_channel(889479625087021106) #Channel where this log will be sent.
        print('Someone updated themselves!')
        title = 'Someone updated themselves!'
        msg = 'There was a disturbance in the force.'
        if before.display_name != after.display_name:
            title = f'Display name change of {after}'
            msg = f'Old display name: {before.display_name}\nNew display name: {after.display_name}'
        if before.status != after.status:
            title = f'Status change for {after}'
            msg = f'Old status: {before.status}\nNew status: {after.status}'
        if before.activity != after.activity:
            title = f'Activity change for {after}'
            msg = f'Old activity: {before.activity}\nNew Activity: {after.activity}'
        
        if self.admin_member_update == True:
            embed = discord.Embed(title= '**Admin Logs**')
            embed.add_field(name=title, value=f'```{msg}```', inline=False)
            await channel.send(embed=embed)
```This isn't reading whenever someone updates their status or activity. It works for display name.
**Yes intents and presence are set properly.** Unless there's a random one that's not members and I have to specifically define..
grand anvil
#

my guess would be intents but you say intents are set properly

drifting arrow
#

@grand anvil listener is the same as bot.event i assume.

#

I'll try and move the bot out of the cog and use bot.event instead

grand anvil
drifting arrow
#

Didnt make a difference

slate swan
grand anvil
grand anvil
slate swan
#
    async def run_once_when_ready(self):
        await bot.wait_until_ready()
        today = datetime.utcnow().strftime("%Y%m%d")
        with open('daily_poll.txt','r') as file:
            if today in daily_poll:
                print(today)
            else:
                print("Cant find it wot?")
        await self.bot.loop.create_task(self.run_once_when_ready())

Final code in case you want to see!

grand anvil
slate swan
grand anvil
#

well I mean you can't call it outside a function. I'd call it in the when_ready listener

karmic nymph
#

im trying to find a way to see if a user has a certain permission in discord.py

#

but the only thing I can find is @slate swan_permissions which doesn't work for me as it's not for a command

#

I just want an if statement to see if they have a permission

velvet sinew
#

How to make cog and add commands?

grand anvil
velvet sinew
#

Yeah

#

What?

stone palm
#

can someone tell me why

#
Ignoring exception in command youtube:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/MathBotDisnake/cogs/youtube.py", line 10, in youtube
    i = await ctx.author.voice.channel.create_invite(target_type=TargetType.embedded_application, target_application_id=755600276941176913, max_age=1800)
NameError: name 'TargetType' is not defined

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

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 'TargetType' is not defined
maiden fable
#

bot.add_command?

stone palm
#

hi hunter... lol

velvet sinew
#

Thnx bro

maiden fable
#

Ah, ok. My bad, didn't read their previous message

stone palm
grand anvil
stone palm
# maiden fable disnake.TargetType......
Ignoring exception in command youtube:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/MathBotDisnake/cogs/youtube.py", line 10, in youtube
    i = await ctx.author.voice.channel.create_invite(target_type=discord.TargetType.embedded_application, target_application_id=755600276941176913, max_age=1800)
AttributeError: module 'discord' has no attribute 'TargetType'

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

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: AttributeError: module 'discord' has no attribute 'TargetType'
maiden fable
#

BTW can anyone here help me make a paginator?

So my API sends some data in the form of a dict, and I want to paginate it in an embed and control it with buttons... I want to show only a maximum of 10-12 entries on one page... Any help?

karmic nymph
#

im just basically making a leaderboard but I dont want moderators to be displayed

slate swan
karmic nymph
#

so if checking for permissions on the user doesn't wor

slate swan
stone palm
karmic nymph
#

Ill just have to check the users id with the mods in the server

maiden fable
#

!d discord.Invite.TargetType @stone palm

unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

maiden fable
#

!d discord.Invite.target_type

unkempt canyonBOT
maiden fable
#

There

stone palm
#

yes

#

what it says is

#

wait what

maiden fable
#

......?

drifting arrow
#

OH

#

I'm using discordpy2.0

maiden fable
#

Cool

stone palm
#

so target_type=discord.InviteTarget.embedded_application?

maiden fable
#

InviteTarget?

grand anvil
#

if this also doesn't work, idk.

NOTE: It won't work with self bots

stone palm
slate swan
#

I dont want on_ready since it will fire multiple times Think I wanted run_once_when_ready

maiden fable
grand anvil
slate swan
#

Okay so I updated my code to this to try something

    async def run_once_when_ready(self):
        await bot.wait_until_ready()
        today = datetime.utcnow().strftime("%Y%m%d")
        with open('daily_poll.txt','r') as file:
            if today in daily_poll:
                print(today)
            else:
                print("Cant find it wot?")
    self.asyncio.run((self.run_once_when_ready())

But since this is in a cog I am getting this error

def setup(bot):
    bot.add_cog(dailypoll(bot))

Error

    def setup(bot):
    ^
SyntaxError: invalid syntax
grand anvil
grand anvil
#

and make sure the def setup isn't inside the Cog class

grand anvil
maiden fable
#

Also won't work

grand anvil
#

first one made no sense I just blindly copied yours cause I'm in class

maiden fable
#

U can't run an async function in the init

slate swan
grand anvil
maiden fable
#

Haha!

grand anvil
#

bro this is kinda annoying ngl

maiden fable
#

Lol

grand anvil
#

@slate swan BTW async def on_ready(self): fires only once in my bot

maiden fable
grand anvil
#

unless you made a super complex bot which can turn on and off without code stopping, you'll be good with listener

maiden fable
#

When my bot sends way too many AI Messages haha

slate swan
#

Its risky since I will be pinging a role and I dont want it to spam more often than it should

maiden fable
#

Yea

#

Don't do it

#

Instead

#

Why not make a task and set the count to 1?

#

And start it at the place where u load your cogs

#

task.start()

grand anvil
maiden fable
#

Simple

grand anvil
#

that's big brain

maiden fable
grand anvil
#

I don't have a lot of experience with asyncio lemon_sentimental

maiden fable
#

Same

grand anvil
#

I used tasks only once in my whole bot and used a lot of google for it

maiden fable
#

Idk shit about it pithink

#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
grand anvil
maiden fable
#

There (:

maiden fable
#
@tasks.loop(count=1) 
async def once():
    print("Working only once") 

once.start() 
#

Ezz

grand anvil
#

I thought its asyncio library 💀

maiden fable
grand anvil
maiden fable
#

Indeed

slate swan
maiden fable
#

U can do that anywhere, as the task.start() isn't async

slate swan
#

Okay time to try that!

maiden fable
#

(:

hasty loom
#

whats the equiv of bot.get_channel or bot.get_guild but for member?

drifting arrow
#

member.guild

hasty loom
#

ah

drifting arrow
#

oh

#

i was close tho

#

And that's all that matters.

grand anvil
#

if you want user, do bot.fetch_user

drifting arrow
#

What's the difference between member and user?

hasty loom
#

member is with guild context

grand anvil
#

member is like server member so like you get member's roles and nickname and stuff

#

and it will return error if the user is not in server

#

whereas user will give the general info like id and stuff and will work for any user on discord

drifting arrow
#

So anybody in the server (say this python server) is read as a member.

slate swan
# maiden fable Indeed
    @tasks.loop(count=1)
    async def once():
        today = datetime.utcnow().strftime("%Y%m%d")
        with open('daily_poll.txt', 'r') as file:
            if today in daily_poll:
                print(today)
            else:
                print("Cant find it wot?")

No error but it doesnt print RS_smh

drifting arrow
#

and once I leave this discord, I'll be regarded as a user (Unless the bot is in a discord I'm in)

grand anvil
#

they'll still be treated as a normal user if you used fetch_user

drifting arrow
slate swan
# drifting arrow wait. where is daily_poll variable?
this_file_directory = Path(__file__).parent.resolve()
other_file = this_file_directory / "daily_poll.txt"
with open(other_file, "r+") as file:
    daily_poll = [daily_poll.strip().lower() for daily_poll in file.readlines()]

Before the class

drifting arrow
#

Okay

grand anvil