Command __ not found - discord

I have a webhook cog for a discord bot I'm making. I want to make the embarrass command (in the webhook cog) trigger a webhook to be created with a user's name and pfp, which is working just fine. however, I also want this command to be able to be set onto a specific user, and that is where the problem arises. When I try to add a member parameter into the embarrass function, so it looks like: async def embarrass(self, ctx, member: discord.Member
it doesn't work. every time I execute the command after that I get a "command embarrass not found" error. this holds true regardless of if I pass through the paramter, and if I add member: discord.Member = None to it to make it not required; nothing I've done works. I would greatly appreciate any help on this topic.
Here is my main.py:
import random
import asyncio
import aiohttp
import json
import keep_alive
from discord import Game
from discord.ext.commands import Bot
import datetime
import re
import time
from subprocess import call
import discord
from discord.ext import commands
from discord.utils import get
import text
import os
TOKEN = os.environ['token']
bot = commands.Bot(command_prefix=".")
startup_extensions = ["Cog.Cog_Template", "Cog.webhooks"]
#bot.event
async def on_ready():
# On read, after startup
print(f"Connecting...\nConnected {bot.user}\n") # Send message on connected
if __name__ == "__main__": # When script is loaded, this will run
for extension in startup_extensions:
try:
bot.load_extension(extension) # Loads cogs successfully
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
keep_alive.keep_alive()
bot.run(TOKEN)
And here is my cog file (its called webhook.py and its in a folder called Cog:
from discord import Webhook, RequestsWebhookAdapter
from discord.ext import commands
import random
embarrasslist = ["I use and throughly like airpods","I respond with \"^\" to everything because I'm too dumb to have an original thought of my own","The only time I ever go outside is for school","I made a discord server where exactly 3 people joined, and they were were my alt accounts.","I get legitimately scared when I play five nights at freddy's","I play PC Games with a steam controller","I unironically use 69 in my usernames","I cried myself to sleep when I found out that my favourite chair had a dent in it","My parent's gave me a PS Move instead of a Wii for christmas","I unironically watch Ali-A","I spam .embarrass because I am very narcissistic and want to see my face on a bot", "I couldn't teach my son how to ride a bike cause I can't ride one myself","I own a sonic pillow and I kiss it every night before I go to sleep","I set my favorite 3ds game to system settings because I thought I was being clever","I set my favorite 3ds game to system settings because I can't buy any more games","Paul Blart: Maul Cop is my favorite movie","I thought shrek 3 wasn't bad","I have a gameinformer subscription","It took me a full day to beat the first level of super mario bros","My favorite emote is :joy:","I spent 2 hours learning how to make a new folder on my computer","I torrented fortnite"]
class WebHooks(commands.Cog, name="WebHooks"):
global embarrasslist
def __init__(self, bot):
self.bot = bot
#commands.command(name="embarrass")
async def embarrass(self, ctx, member: discord.Member = None):
"""Send a message as a webhook"""
if member != None:
user = member
elif member = None:
user = ctx.message.author
embarrassnumber = random.randint(0,21)
embarrassment = embarrasslist[embarrassnumber]
looking_webhooks = await ctx.channel.webhooks()
if looking_webhooks:
for webhook in looking_webhooks:
if webhook.name == "NexInfinite-GitHub":
await send_webhook(webhook, embarrassment, ctx, user)
return
else:
pass
webhook = await ctx.channel.create_webhook(name="NexInfinite-GitHub")
await send_webhook(webhook, embarrassment, ctx, user)
return
#commands.command(name="embaras", aliases = ["embarras","embarass"])
async def embarras(self, ctx):
"""Send a message as a webhook"""
cantspell = "I don't know how to spell *embarrass* properly"
looking_webhooks = await ctx.channel.webhooks()
if looking_webhooks:
for webhook in looking_webhooks:
if webhook.name == "NexInfinite-GitHub":
await send_webhook(webhook, cantspell, ctx)
return
else:
pass
webhook = await ctx.channel.create_webhook(name="NexInfinite-GitHub")
await send_webhook(webhook, cantspell, ctx)
return
def setup(bot):
bot.add_cog(WebHooks(bot))
async def send_webhook(webhook, message, ctx, uservar):
webhook_id = webhook.id
webhook_token = webhook.token
webhook = Webhook.partial(int(webhook_id),
f"{webhook_token}",
adapter=RequestsWebhookAdapter())
webhook.send(f'{message}', username=f"{ctx.uservar.display_name}",
avatar_url=ctx.uservar.avatar_url) # Sends the message as the author
I am running this on repl.it so thats why I import keep_alive, and I have another cog that I added with other commands but that doesn’t seem to be the issue either. I can add it if you request it however.
Thanks for the help!

I forgot to import discord at the top, so I couldn't successfully use discord.Member. Importing discord solved this issue.

Related

Commands not working after updating to discord.py 2.0

I was trying to change my version from 1.7.3 to 2.0+ using pip install -U git+https://github.com/Rapptz/discord.py. Usually when I did this there would be an error about intents that would pop up, but instead there were no errors but it said:
discord.client logging in using static token
2022-12-20 12:34:14 INFO
discord.gateway Shard ID None has connected to Gateway (Session ID:6837cbf3ad28b9040ceb5e044dffe90f).
After that, any commands that I used didnt get responded to, as it worked perfectly fine in 1.7.3.
My code:
import discord, os, requests, json, random, time, datetime
from discord.ext import commands
from replit import db
import urllib
import asyncio
from discord import Member
from discord.ui import Select,Button,View
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="e!",
intents=intents)
client = discord.Client(intents=intents)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('whats the meaning of life'):
await message.channel.send(
'The meaning of life is "freedom from suffering" through apatheia (Gr: απαθεια), that is, being objective and having "clear judgement", not indifference. - Wikipedia.'
)
time.sleep(2)
await message.channel.send(
'There, someone just explained your life. Kind of depressing, isnt it?'
)
basically you don't have the correct intents to be able to send message with the bot
you need to have the discord.Intents.all()
and please don't use the time.sleep in an asynchronous function use asycio.sleep()
import asyncio
bot = commands.Bot('e!',intents=discord.Intents.all())
#bot.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('whats the meaning of life'):
await message.channel.send(
'The meaning of life is "freedom from suffering" through apatheia (Gr: απαθεια), that is, being objective and having "clear judgement", not indifference. - Wikipedia.'
)
await asyncio.sleep(2)
await message.channel.send(
'There, someone just explained your life. Kind of depressing, isnt it?'
)

Extentions and Cogs not working in discord.py v2

I am trying to get export my troll commands in a discord bot i run to a new file, using cogs and extensions. However, the commands do not register, and I'm not sure why. I'll send the code here. (just ignore the weird function launch, it makes more sense when you look at the bot entirely but its spread thought 2k lines. )
#bot.py
import os
import sys
import time
import datetime
import discord
from discord.ext.commands import Bot
from discord import Intents
import assets
import role_counter
from discord.ext import commands
import discord.ext.commands
from dotenv import load_dotenv
import git_push
import merit_config
import trolls
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
TOKEN_TEST = os.getenv('DISCORD_TOKEN_TEST')
GUILD = os.getenv('DISCORD_GUILD')
cogs = ['cogs.trolls']
def startup(START):
global LAUNCH
global bot
if START == TOKEN:
intents = Intents.all()
bot = commands.Bot(intents=intents, command_prefix='.')
bot.remove_command('help')
LAUNCH = TOKEN
startup(TOKEN)
initial_extensions = ['cogs.trolls']
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension)
def main():
while True:
bot.run(LAUNCH)
#trolls.py
import assets
from discord.ext import commands
class troll_commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def troll(self, ctx):
if ctx.channel.id == '936902313589764146' or '939028644175699968':
await ctx.send(f"```{assets.troll_command()}```")
await self.bot.process_commands()
def setup(bot):
bot.add_cog(troll_commands(bot))
I've mirrored every example i can find, it just isn't working and idk why. If I'm missing some code to reporodce please just tell me, ill edit this post.
It depends on the version you're currently using but as you're having issues, you need to clarify what sort of error you're getting.
If you're using V2 then you do need to use async for the majority of your code now, here's a migration guide if you would like to take a look: https://discordpy.readthedocs.io/en/stable/migrating.html.
The main areas that you need to fix are:
if __name__ == '__main__':
for extension in initial_extensions:
bot.load_extension(extension) # you need to await this
def main(): # you aren't ever calling main
while True:
bot.run(LAUNCH)
and
def setup(bot): # needs to be async
bot.add_cog(troll_commands(bot)) # needs to be awaited
There are some other things you should reconsider like global vars but this should work for now.
You have to use async and await to be able to add a cog.
You have to async and await the extension loading and running the bot
await bot.load_extension(extension)
async def setup(bot):
await bot.add_cog(Command(bot))

How to create a specific Discord bot that can create a note on a discord account which anyone/any admins can read

I want to create a discord bot in which you can create a note on accounts. Say i wanna make a not on user user#1111, i would do something like !note #user#1111 New note. I want to make it in python but im not too sure if i can do it on there? Thanks!
Edit: Anyways, my answer was really bad since I provided a false example. Well, it is because I don’t really use SQL, I only know how to use to replit database. And if you are on replit, the following code will work for you; if not, you can’t use this code.
import discord
from replit import db
from discord.ext import commands
bot = commands.Bot(command_prefix="n!")
#bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
#bot.command()
async def note(ctx, user: discord.User, *, content):
if str(user.id) not in db.keys(): # If the user ID is not in the keys of the database:
db[str(user.id)] = {str(ctx.author.id):content}
else:
dic = db[str(user.id)]
dic[str(ctx.author.id)] = content
db[str(user.id)] = dic
await ctx.send(f"Saved your note for {user}: {content}")
bot.run("TOKEN")
Old answer (bad)
You can use a database like SQL. You can just make a command and saves the content entered after the command to the database. This is my example (I am using replit instead of SQL. **Don’t use this.**):
import discord
from replit import db
from discord.ext import commands
bot = commands.Bot(command_prefix="n!")
#bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
#bot.command()
async def note(ctx, user: discord.User, content):
db[str(user.id)] = {str(ctx.author.id):content}
bot.run("TOKEN")
MY EXAMPLE IS REALLY BAD. IT WILL OVERRIDE THE DATABASE EVERYTIME SOMEONE USES THE COMMAND. DON’T COPY THIS CODE. TRY TO CODE IT YOURSELF.

'Member' object has no attribute 'hasPermission'

i wanted to make a bot to discord for delete messages easly. it works 3 months ago but now i got an error " 'Member' object has no attribute 'hasPermission' ". thanks for everyone to share opinion. have a nice day.
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
if message.content.startswith('botcuksil'):
if (message.author.hasPermission('MANAGE_MESSAGES')):
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
It is throwing 'Member' object has no attribute 'hasPermission' this error because 'Member' does not have an attribute named 'hasPermission'. To fix your problem, I have re-written your code and also given some explanation below the code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
#client.event # we need to add and check for a client event
async def on_message(): # we need to execute the command when we recieve an message so we define a function called 'async def on_message():'
if message.content.startswith('botcuksil'):
if message.author.guild_permissions.manage_messages: # we need 'author.guild_permissions.(permission)' intead of 'if (message.author.hasPermission('MANAGE_MESSAGES'))'
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
I have not tested this yet, but according to me, your problem: 'Member' object has no attribute 'hasPermission' should be solved.
What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Summary of what I have done:
I have added a client event (#client.event) and an async function on_message().
What it does is it checks if it is getting an message or not. If it detects a new message in any of the servers it is invited to, it triggers the code in on_message().
As I said: What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Instead of writing that, we can use message.author.guild_permissions.manage_messages. It checks if the message author's server's permissions include "manage_messages". Hope my solution fixes your problem.
Always happy to help!
-sqd mountains

Push images to server from a specific folders via discord.py

I have some problems with my discord bot, I'll try to explain as much as I can.
So i have a bot's folder, which contains a bot itself, and a folder named commands, basically it's where my cogs are stored, and inside the folder commands there is a folder named images, in which i saved images for my bot to pick randomly. the problem is that i couldn't manage to tell the bot to take images from that specific folder, and instead it only works if i put images directly into bot's folder (the first folder). I've tried many things, such as:
#commands.command()
async def randomimage(self, ctx):
for list os.listdir(./commands/images/):
list = (images here)
await ctx.send('take this', file=discord.File(random.choice(list)))
but that didn't help either, i can just put /commands/images/(image) to every image but the list is huge and i don't want to write path to every image there.
bot:
#!/usr/bin/python3.6
import discord
from dotenv import load_dotenv
import random
from discord.ext import commands
import os
load_dotenv()
TOKEN = os.getenv('TOKEN')
bot = commands.Bot(command_prefix = '.')
#this script types "Connected!" in terminal if nothing has gone wrong
#bot.event
async def on_ready():
print('Connected!')
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
bot.run(TOKEN)
the whole command:
import discord
import os
import random
from discord.ext import commands
class randomimage(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def randomimage(self, ctx):
#waiting for suggestion on this line
list = (image list)
await ctx.send('take this', file=discord.File(random.choice(list)))
def setup(client):
client.add_cog(randomimage(client))
I'm kind of noob here so any help would be greatly appreciated
I've figured this out. Apparently answer was as easy as changing a directory, literally
I've used os.chdir('./commands/images') and it worked.
Edit: Apparently I was wrong and that didn't work either
Update: apparently os.chdir works, but I have to specify the full path, like /home/user/discordbot/commands/images, so yes, that works

Resources