How to get user activity in discord.py? - python

I'm trying to make a bot that will write to the chat what the user is playing, but even when the game is running, None is displayed all the time
What am I doing wrong?
Working code:
from discord.ext import tasks
import discord
intents = discord.Intents.all()
intents.presences = True
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
#tasks.loop(seconds=5)
async def activity_task(self, message):
mentions = message.mentions
if len(mentions) == 0:
await message.reply("Remember to give someone to get status!")
else:
activ = mentions[0].activity
if activ is None:
await message.reply("None")
else:
await message.reply(activ.name)
#activity_task.before_loop
async def before_my_task(self):
await self.wait_until_ready()
async def on_message(self, message):
if message.content.startswith('!status'):
self.activity_task.start(message)
client = MyClient(intents=intents)
client.run('token')

As Ceres said, you need to allow intents.
Go to your developer's page https://discord.com/developers/applications, and go to the bot. Scroll down a bit, and you'll see this:
Turn on presence and server members intent.
Now, in your code, you'll have to add this in the beginning:
intents = discord.Intents.all()
Change your bot startup code to this
client = MyClient(intents=intents)
Now, with the intents, you want the OTHER person's activity.
So, in the activity_task method, you can't use message.author, as that will return whoever sent the message, not who you're mentioning.
Change it to this:
async def activity_task(self, message):
mentions = message.mentions
if len(mentions) == 0:
await message.reply("Remember to give someone to get status!")
else:
activ = mentions[0].activity
if activ == None:
await messag.reply("None")
else:
await message.reply(activ.name)
Now, if you do !status #[valid ping here], it should return whatever they're doing. Must note: it MUST be a valid ping.

Related

discord.py based bot doesn't work after 2.0 update

So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['ffs','gdsgds']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
client = discord.Client(intents=discord.Intents.default())
client.run('OTkxfsa9WC5G34')
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return 'dont forget uptime robot monitor'
def run():
app.run(host='0.0.0.0',port=8000)
def keep_alive():
t = Thread(target=run)
t.start()
I tried to fix it by my own by changing this line
client = discord.Client(intents=discord.Intents.default())
It has to be some trivial syntax mistake, but I cannot locate it
Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['fdsfds','fsa']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents = intents)
client.run('OTkxMDcxMTUx')
If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents.
intents = discord.Intents.default()
intents.message_content = True
Don't forget to enable it on your bot's developer portal as well.
Also all of that keep alive & flask stuff hints that you're abusing an online host to run a bot on. This brings loads of issues along with it that you can't fix so you should really consider moving away from that. There's posts on a daily basis of people with problems caused by this.
Your code should be:
import discord
from discord.ext import commands # you need to import this to be able to use commands and events
from keep_alive import keep_alive
client = commands.Bot(intents=discord.Intents.default())
#bot.event
async def on_ready(): # you don't need self in here
print('bot is online now', client.user) # you can just use client.user
#bot.event
async def on_message(message): # again, you do not need self
word_list = ['ffs','gdsgds']
if message.author == client.user: # you can use client.user here too
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
keep_alive()
client.run('OTkxfsa9WC5G34') #if this is your real token/you have been using this token since you made the bot, you should definitely generate a new one
To help you, I added some comments to help show you what I have changed and why. As one of the comments in the code says, you should regenerate your bot token at the Discord Developer Portal.
For more info about migrating to 2.0, read the Discord.Py docs

Not able to DM or direct messages in discord.py-self latest version

i am not been able to send dm it gives me an error using module discord.py-self
here is the code
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('BOT IS RUNNING')
async def on_message(self, message):
if message.content.startswith('.hello'):
await message.channel.send('Hello!', mention_author=True)
for member in message.guild.members:
if (member.id != self.user.id):
user = client.get_user(member.id)
await user.send('hllo')
client = MyClient()
client.run('my token')
error
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0)
In server it is only me and a offilne bot i trying to send a message to bot (as you can see in code)
I would try defining your bot like this:
import discord
from discord.ext import commands
## (Make sure you define your intents)
intents = discord.Intents.default()
# What I always add for example:
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
## Define your bot here
client = commands.Bot(command_prefix= '.', description="Description.", intents=intents)
## Run bot here
client.run(TOKEN)
Then, instead of rendering a client on_message event, I'd instead just set it up like a command which will utilize the prefix as defined for the bot above.
#client.command()
async def hello(ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Better practice: (in my opinion)
Use cogs to keep your code neat. Set up this command in an entirely different file (say within a /commands folder for instance):
/commands/hello.py
import discord
from discord.ext import commands
class HelloCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def hello(self, ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Then import the cog into your main file:
from commands.hello import HelloCog
client.add_cog(HelloCog(client))
Hope this helps.

Discord.py trying to get the arriving messages from X GUILD and Y CHANNEL which I do not own through a bot

I'm trying to get the arriving messages from X guild and Y channel that i do not own in Discord through a bot.
Here's the current code:
import discord
import asyncio
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def my_background_task(self):
await self.wait_until_ready()
msg = await self.get_channel(818581199751479299).history(limit=1).flatten()
msg = msg[0]
print(msg)
await self.close() # close client once we are done
client = MyClient()
client.run('BOT_TOKEN')
At the moment I've this code but my_background_task never executes, so what should i do to solve this issue?
The thing I want to do is pretty simple but I can't solve it alone with my current knowledge.
Also, when I try to execute the line:
msg = await self.get_channel(818581199751479299).history(limit=1).flatten()
it says me that history attribute is not found.
Well, let's see if I can solve all of this, thank you all for your help :)

Verification using Python Discord

I'm making a bot with python and I need help with two things.
Making a welcome message for users that include mentioning the user and mentioning the channel
Making a command that will remove the role "Unverified" and add 4 other roles. I also need it to send a message in the verification channel to make sure the person has been verified and send an embed in general chat telling the user to get self roles.
Well you could try
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix=".")
confirmEmoji = '\U00002705'
#client.event()
async def on_ready():
print("[Status] Ready")
#client.event()
async def on_member_join(ctx, member):
channel = get(ctx.guild.channels,name="Welcome")
await channel.send(f"{member.mention} has joined")
#client.command()
async def ConfirmMessage(ctx):
global confirmEmoji
message = await ctx.send("Confirm")
await message.add_reaction(emoji=confirmEmoji)
def check(reaction, user):
if reaction.emoji == confirmEmoji:
return True
else:
return False
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=check, timeout=10)
roleToRemove = get(ctx.guild.roles,name="unverified")
memberToRemoveRole = get(ctx.guild.members,name=user.display_name)
await memberToRemoveRole.remove_roles(roleToRemove)
Now all you have to do is go to the channel and enter .ConfirmMessage

I have a problem with the message.content in python for a discord bot

When I make a loop the message.content never refreshes.
I tried a lot of things but I don't really know how to code in Python.
import discord
import time
i = 0
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'start':
while True:
print(str(message.content))
client = MyClient()
client.run('TOKEN')
I want to see the message.content refresh when I retype a message in Discord. Can somebody helps me please?
I haven't made a bot as a class, but I've always used # operators before defining functions. My bot looks more like this:
#bot.event # I think this is important
async def on_ready():
await bot.change_presence(game=discord.Game(name="with your mom"))
print(bot.user.name + ' is now up and running')
#bot.command(pass_context=True, description='stuff') # again I think this is important
async def process_command(ctx): # pass context of message into bot
print(dir(ctx)) # show what methods are available (or just look up documentation)
print(ctx)

Categories

Resources