Discord API. exception error on on_member_remove() - python

import discord
from discord.ext import commands
intents = discord.Intents(
messages = True,
guilds = True, reactions = True,
members = True, presences = True
)
bot = commands.Bot(command_prefix = "[", intents = intents)
#bot.event
async def on_ready():
print("Bot ready")
#bot.event
async def on_member_join(member):
print(f"{member} is ___")
#bot.event
async def on_member_remove():
print("xxx")
if member.id == 341212492212600832:
invitelink = discord.TextChannel.create_invite(max_uses=1,unique=True)
await member.send(f"you ___ bro. Here u go {inviteLink}")
bot.run("TOKEN")
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "C:\Users\Filbert\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_remove() takes 0 positional arguments but 1 was given

As the error said, on_member_remove takes 1 positional argument member
#bot.event
async def on_member_remove(member): # You forgot to pass it
# ...
Reference:
on_member_remove

Similar to on_member_join, on_member_remove gets passed member, as said in the docs. After fixing this issue, regenerate your token, as you included it in the original post.
Another issue: You shouldn't be creating an instance of discord.TextChannel. Instead, get that channel using bot.get_channel(id), and call create_invite on the TextChannel instance that get_channel returns.

Related

error with discord.py NoneType object has no attribute 'id'

Ok, so I try to make a command with on_message, I put await bot.process_commands(message). But it always raises the 'NoneType' object has no attribute 'id'.
import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.message_content = True
activity = discord.Activity(name='null, dying, trying to fix me', type=discord.ActivityType.watching)
client = discord.Client(intents=intents, activity = activity)
bot = commands.Bot(intents=intents,command_prefix='!')
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
channel = client.get_channel(956302622170701946)
await channel.send(f'connected successfully as {client.user.name}#{client.user.discriminator}')
#client.event
async def on_message(message):
await bot.process_commands(message)
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send("hello stopid")
elif message.content.startswith('die'):
await message.channel.send('ok :sob: i ded now')
await client.close()
#bot.command
async def a(ctx):
await ctx.send("a")
client.run(TOKEN)
this is the entire error:
2022-12-08 18:15:54 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\xxxxx\source\repos\DBot\discordbot.py", line 25, in on_message
await bot.process_commands(message)
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\ext\commands\bot.py", line 1389, in process_commands
ctx = await self.get_context(message)
File "C:\Users\xxxxx\source\repos\DBot\DiscordBot\lib\site-packages\discord\ext\commands\bot.py", line 1285, in get_context
if origin.author.id == self.user.id: # type: ignore
AttributeError: 'NoneType' object has no attribute 'id'
i just want a command with the prefix '$' and sends back the args sent by the user
i probably did something stupid but still thanks.
You only need the bot instance, client is unnecessary. CommandsBot is just upgraded discord.Client and also includes the #bot.event decorator
remove client.close() and move bot.process_commands(message) to the bottom of your on_message function
*Note you should not be doing anything else than prints in on_ready since that fires multiple times

discord.py: show messages counter in a channel

I'm a complete beginner in discord.py, I create a bot and try to count all messages posted in a channel. The bot will show this counter in a message when I call it with the command "!bot".
It works with the simple example "ping" (send "pong" successfully), but when I send "!bot" it returns an error in console:
[2022-09-09 16:59:37] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Rinnosuke\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "D:\Programmation\Python\Discord-bot\bot4.py", line 29, in on_message
message_count()
TypeError: __call__() missing 1 required positional argument: 'context'
This is my code, what arguments should I pass to the message_count function call?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
prefix = "!b"
needed_intents = discord.Intents.default()
bot = commands.Bot(command_prefix=prefix, intents=needed_intents)
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == "ping":
await message.channel.send('pong')
if "!bot" in message.content:
message_count()
#bot.command()
async def message_count(ctx, channel: discord.TextChannel=None):
channel = bot.get_channel(586577242910359564)
count = 0
async for _ in channel.history(limit=None):
count += 1
await message.channel.send("There were {} messages in {}".format(count, channel.mention))
client.run('my token')
bot.run('my token')
Thanks!
You can't include this channel: discord.TextChannel=None You can either set its type or set its value, not both.

How can I ignore the ctx argument from discord.py?

Here is the full script:
from discord.ext.commands import Bot
import tracemalloc
tracemalloc.start()
client = Bot(command_prefix='$')
TOKEN = ''
#client.event
async def on_ready():
print(f'Bot connected as {client.user}')
#client.command(pass_context=True)
async def yt(ctx, url):
author = ctx.message.author
voice_channel = author.voice_channel
vc = await client.join_voice_channel(voice_channel)
player = await vc.create_ytdl_player(url)
player.start()
#client.event
async def on_message(message):
if message.content == 'play':
await yt("youtubeurl")
client.run(TOKEN)
When I run this script, it works fine. When I type play in the chat, I get this error:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\bot.py", line 26, in on_message
await yt("youtubeurl")
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 374, in __call__
return await self.callback(*args, **kwargs)
TypeError: yt() missing 1 required positional argument: 'url'
How do I fix this? So far all I have tried is added the argument * between ctx and url, which didn't fix it
It is not possible to "ignore" the context argument, why are you invoking the command in the on_message event?
You can get the context with Bot.get_context
#client.event
async def on_message(message):
ctx = await client.get_context(message)
if message.content == 'play':
yt(ctx, "url")
I'm guessing your commands aren't working cause you didn't add process_commands at the end of the on_message event
#client.event
async def on_message(message):
# ... PS: Don't add the if statements for the commands, it's useless
await client.process_commands(message)
Every command should be working from now on.
Reference:
Bot.get_context
Bot.process_commands

Non-Prefixed messages on Disxord.py

#client.event
async def on_message(message,channel):
if message.content.startswith("sa"):
await channel.send(message.channel, "as")
await client.process_commands(message)
This code should say as when I say sa. It detects the word but it doesn't respond. This is the error I'm getting:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\---\PycharmProjects\discordmasterbot\venv\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'channel'
I'm thinking It might be an outdated code so I tried to change it as new as possible but I'm getting that error.
#client.event
async def on_message(message):
if message.content.startswith('sa'):
await message.channel.send('as')
await client.process_commands(message)
I don't know where you had got the code from but an old project I did in 2018 uses this function signature:
client = discord.Client()
#client.event
async def on_message(message):
if message.content.startswith("sa"):
await client.send_message(message.channel, "as")
However, since then, it looks like discord.py has migrated to a new version. Here is the new way to do it from the quickstart documentation:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
So what you want is probably the last few parts:
#client.event
async def on_message(message):
if message.content.startswith('sa'):
await message.channel.send('as')
EDIT
It looks like your code also got the process_commands part wrong. process_commands is a method of discord.ext.commands.Bot, not client. So it should be bot.process_commands(message).

AttributeError: 'list' object has no attribute 'channel' discord.py

I am trying to create a function that would clear the chat on discord using https://www.youtube.com/watch?v=ZBVaH6nToyM , however I think that I've declared channel (channel = ctx.message.channel) however entering .clear would result in an error
Ignoring exception in command clear
Traceback (most recent call last):
File "C:\Users\mark\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\discord\ext\commands\core.py", line 50, in
wrapped
ret = yield from coro(*args, **kwargs)
File "C:/Users/mark/Desktop/purge.py", line 17, in clear
await client.delete_message(messages)
File "C:\Users\mark\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\discord\client.py", line 1261, in delete_message
channel = message.channel
AttributeError: 'list' object has no attribute 'channel
import discord
from discord.ext import commands
from discord.ext.commands import Bot
TOKEN = "token here"
client = commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print("Bot is online")
#client.command(pass_context = True)
async def clear(ctx, amount=100):
channel = ctx.message.channel
messages = []
async for message in client.logs_from(channel,limit=int(amount)):
messages.append(messages)
await client.delete_message(messages)
await client.say('message has been deleted')
client.run(TOKEN)
You are basically appending a list itself over and over again
my_list=[]
my_list.append(my_list)
print(my_list)
Which results in something like this
>>[[[...]]
The command should be something like this
#bot.command(pass_context=True)
async def clear(msg,amt:int=20): #can be converted into int via :type
messages=[]
async for i in bot.logs_from(msg.message.channel,limit=amt):
messages.append(i)
await bot.delete_messages(messages)
Also a heads up note, you can't bulk delete messages that are older than 14 days I think meaning that you can't use the delete_messages and only delete it individually

Categories