Get User Activity from User ID - Discord.py - discord

I want to a user's current activity (Playing Game, Online, Offline) from the user ID. I have all intents enabled. Here's my code which doesn't work:
member1 = bot.get_user(5242612345674376)
print(member1.activity)
Output:
Initating BOT
'Bot Connected!'
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\Projects\newtest.py", line 33, in on_ready
print(member1.activity)
AttributeError: 'User' object has no attribute 'activity'
Any kind of help is appreciated

you can't get a user activity with discord.User. so use discord.Member:
user = bot.get_user(5242612345674376) # get user
mutual_guild = user.mutual_guilds[0] # get a mutual server
member = discord.utils.get(mutual_guild.members(), id=user.id)
# get user as a member with first mutual guild and id number
print(member.activity)

I have figured it out. Here is the code
#Using it on on_message() or you can use GuildID or just guilds
guild = bot.get_guild(message.guild.id)
#Member's UserID here
member1 = guild.get_member(0123456789)
print(member1.activities)

Related

AttributeError: 'NoneType' object has no attribute 'roles' Discord Self-Bot

Am using discord.py library to create a Discord self-bot that reads through a .txt file I already have filled with Discord IDs and checks their role in a guild server, if the role matches the role am looking for then their ID is saved in a new notepad called 'roletrue.txt'. I have been stuck for quite some time now, any help is appreciated! I know it is against Terms of Services however I still do it.
Code:
import discord
client = discord.Client()
#client.event
async def on_ready():
# Read the file containing the Discord IDs
with open("ids.txt", "r") as f:
ids = f.read().split("\n")
# Get the guild and the role
guild = client.get_guild('GUILD_ID')
role = discord.utils.get(guild.roles, name="ROLE_NAME")
# Iterate through the IDs
for id in ids:
# Get the member from the guild
member = await guild.fetch_member(int(id))
if role in member.roles:
with open("roletrue.txt", "a") as f:
f.write(f"{id}\n")
print(f"Discord ID {id} has the role {role.name}.")
else:
print(f"Discord ID {id} does not have the role {role.name}.")
client.run("TOKEN", bot = False)
Error:
File "C:\Users\spath\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\spath\OneDrive\Υπολογιστής\NFT Vict Scrape\checkroles.py", line 13, in on_ready
role = discord.utils.get(guild.roles, name="Customer")
^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'roles'
I tried rewriting the code from scratch and check discord library and searched online and couldn't find a answer for my problem.
Change
guild = client.get_guild("GUILD_ID")
to
guild = await client.fetch_guild("GUILD_ID")
Get only returns the guild object if it's cached - if it's returning None then it's not so use fetch instead.
You will have to use await in order to fetch guild id and the roles from it,
try using this:
guild = await client.fetch_guild("GUILD_ID")
or if it doesn't work, try using discord utils.

Discord.py Ban and Hackban command error // AttributeError: 'NoneType' object has no attribute 'ban'

I'm not sure what the issue is as this works perfectly for all my other bots! Does anyone know how to fix this.
#client.command(description="Bans People!") # Bans people
#commands.has_any_role('Staff')
async def ban(ctx, x: typing.Union[discord.Member, int], *, reason=None):
guild = client.get_guild(1037550844935147622)
if x in ctx.guild.members:
await x.ban(reason=reason)
await ctx.send(f'Banned {x.mention}')
else:
await guild.ban(discord.Object(id=x))
await ctx.reply(f'User has been hackbanned!\nUser: <#{x}>')
Ignoring exception in command ban:
Traceback (most recent call last):
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 184, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\13129\Desktop\Python Bot\will.py", line 398, in ban
await guild.ban(discord.Object(id=x))
AttributeError: 'NoneType' object has no attribute 'ban'
What I was expecting was to have the person banned outside of the server. It just doesn't work but works with my other bots.
You Need Convert The ID Object To User Object \
from discord.utils import get
user = get(bot.get_all_members(), id="your id")
User Object Has Ban Method Not The ID

AttributeError: 'function' object has no attribute 'send' - Discord,py Bot error

channel = client.get_channel
if message.content.lower().startswith('experiment'):
moji = await client.get_channel.send("https://c.tenor.com/R_itimARcLAAAAAd/talking-ben-yes.gif")
emoji = [":blue_circle:"]
for experiment in emoji:
await client.add_reaction(emoji)
What I want the bot to do is when the user types 'experiment' the bot will send the link to the photo and it will attach the emoji to it. It gives me this error.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\13129\Desktop\Python Bot\Ben.py", line 50, in on_message
moji = await client.get_channel.send("https://c.tenor.com/R_itimARcLAAAAAd/talking-ben-yes.gif")
AttributeError: 'function' object has no attribute 'send'
I tried changing a few things on line 20 but nothing seems to be working!
Bot.get_channel is a method which takes a channel_id as a positional argument and gets you a Union[StageChannel, VoiceChannel, CategoryChannel, TextChannel, Thread (if you are on master)] if the ID you pass to it matches one it has in its internal cache (this requeires members intent)
you can't do
get_channel.send(), get_channel is a method, or in other words, a bound function to Bot class.
here is an example usage:
channel = bot.get_channel(CHANNEL_ID)
await channel.send("hello there!")
also,
client.add_reaction(emoji) is not a thing
Message.add_reaction is. await channel.send() returns a Message object which you can store in a variable and then add your emoji
message = await channel.send("hello there!")
for emo in emoji:
await message.add_reaction(emo)
and I am pretty sure that you need the unicode of that emoji and the string would raise UnknownEmoji error, but if it doesn't then it's fine. If it does though, just use "\N{Large Blue Circle}" instead :blue_circle: and that should fix it.
You should be doing client.get_channel() with something in the brackets like a channel ID, not client.get_channel If not how will they know what channel to send it to.
For Prefixed Commands
#client.command()
async def command_name(ctx)
await ctx.send()
# Sends to what ever channel the command was sent in

Discord.py Give role if member customstatus contains hi

Im working on a Loop that checks every 5 seconds if user Status contain "hi" if so it should give the user a role.
I dont really know how to do it, But maybe someone can help.
My code:
#Here is a little base for the Command i asked...
#I hope it can help you
#tasks.loop(seconds=15)
async def status_role():
if "hi" in ???.lower()
#here comes the code
#(Idk what the code is so i asked you guys :D)
member = ctx.message.author
role = get(member.server.roles, name="Friendly dude")
await bot.add_roles(member, role)
Looking at your new error, you're getting an IndexError because one of your members doesn't have an activity set, so activities[0] doesn't exist. Use an if-statement to check this. To see if a tuple is empty, you can just do if tuple (as empty lists/tuples are falsy), so the code below should solve that:
#tasks.loop(seconds=15)
async def status_role():
guild = client.get_guild(your guilds id)
role = get(guild.roles, name='Friendly dude')
for member in guild.members:
if member.activities and 'hi' in member.activities[0].name.lower():
await member.add_roles(role)
In addition to the fragment in the answer above.
EDIT: Apparently you didn't get my above ^ sentence saying it was meant to be combined with the other answer, so I've edited my answer & combined it myself. This should be the correct answer to your question.
Still same error
Unhandled exception in internal background task 'status_role'.
Traceback (most recent call last):
File "C:\Users\lequi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\lequi\Desktop\Programs\Clipox\ClipoxMain\main.py", line 136, in status_role
[await member.add_roles(role) for member in guild.members if 'hi' in member.activities[0].name.lower()]
File "C:\Users\lequi\Desktop\Programs\Clipox\ClipoxMain\main.py", line 136, in <listcomp>
[await member.add_roles(role) for member in guild.members if 'hi' in member.activities[0].name.lower()]
IndexError: tuple index out of range
You can use member.activities. This will return you a list of member's activities. As far as I know, you can get custom status with member.avtivities[0].name. This'll return you a string of member's custom activity.
Also, you can't use ctx.message.author. You need to iterate through members in the guild to check every one of their's activity.
So you can simply do:
#tasks.loop(seconds=15)
async def status_role():
guild = client.get_guild(your guilds id)
role = get(guild.roles, name='Friendly dude')
[await member.add_roles(role) for member in guild.members if 'hi' in member.activities[0].name.lower()]
EDIT
There're some updates about Intents in the discord.py 1.5.x. You need to define it before defining client = discord.Bot(prefix='') to get guilds, channels etc.
import discord
intents = discord.Intents().all()
client = discord.Bot(prefix='', intents=intents)
EDIT 2
If member has no status, it'll return an empty tuple, that's why you get IndexError. To prevent this, you can add a simple if block to your code.
async def status_role():
guild = client.get_guild(your guilds id)
role = get(guild.roles, name='Friendly dude')
[await member.add_roles(role) for member in guild.members if member.activities[0] and 'hi' in member.activities[0].name.lower()]

Trying to set up permissions for a discord bot but can't seem to be able to

So I'm making a discord bot for a server that I use and wanted to add a censor feature so that if a user said something in the "bannedWords" list while not in a specific channel (working) it would edit the message to have "[redacted]" in its place. I believe the code itself is working but I get this error message every time I test it. I've tried adding permissions via the Discord Developer Portal (selecting "OAuth2," choosing the "bot" scope, and the manage roles, view channels, send messages, manage messages, read message history, and mention everyone permissions), copied the link and added it to my testing server but it still didn't seem to work along with having the proper permissions via role.
Full Error:
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Me\Desktop\Productive\Programming Projects\Python 3\Other\MyBot\bot.py", line 32, in on_message
await message.edit(content = editedMessage)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\message.py", line 843, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
Code
import discord
bot=discord.Client()
#bot.event
async def on_ready():
print('Logged in')
print("Username: %s" % (bot.user.name))
print("Userid: %s" % (bot.user.id))
#bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
bannedWords=['chink','dyke','fag','ook','molest','nig','rape','retard','spic','zipperhead','tranny']
print(str(message))
print(str(message.content))
if "name='no-rules-lol'" not in str(message): #probably a better way to do this but it works
for word in bannedWords:
if word in message.content.lower():
await message.channel.send('{0.author.mention}, you have used a word that is black-listed please read <#754763230169006210> to get a full list of black-listed words'.format(message))
#await message.edit(content = message + 'this has been edited')
editedMessage=str(message.content.replace(word,'[redacted]'))
await message.edit(content = editedMessage)
bot.run(Token)
You cannot edit a message that is not sent by the bot.
Instead, just try deleting the message.
await message.delete()
It is as easy as that.
If you are adding more commands into your bot, you can just add this to your on_message at last:
await bot.process_commands(message)
Thank you.

Resources