Looping through guild members with discord.py - python

I have been attempting to make a bot that will give all users in my small guild (<50 members) a role.
I have had a tough time getting the bot to loop through all of the users in the server.
Currently it will output:
02/06/21 17:09:23: Successfully gave john_doe#1234 DJ role. (1 users!).
02/06/21 17:09:23: user john_doe#2234 gave all (1) users DJ role. (placeholder1).
Any advice?
Here is the part of the code I am working on:
if message.content.startswith(prefix + "Give DJ ALL"):
count = 0
for member in message.guild.members:
count = count + 1
await member.add_roles(discord.utils.get(message.guild.roles, name = "DJ"))
print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "Successfully gave " + str(member) + " DJ role. (" + str(count) + " users!).")
await message.channel.send("Successfully gave " + str(count) + " users DJ!")
print(str(datetime.datetime.now().strftime("%x %X")) + ": " + "user " + str(message.author) + " gave all ("+ str(count) + ") users DJ role. (" + str(message.guild.name) + ").")
edit: yes i have enabled intents in my bot settings on the website
alonside this:
async def on_ready():
intents = discord.Intents.default()
intents.presences = True
intents.members = True

Fixed by using proper syntax thanks to Łukasz Kwieciński.
code here:
client = discord.Client(intents = discord.Intents.all())

Related

how to identify and download images in telehton newMessage event?

I wrote a simple python script to save all messages seen by a user to files using an telethon event handler:
#CLIENT.on(events.NewMessage)
async def my_event_handler(event):
sender = await event.get_sender()
chat_id = event.chat_id
out ='\n\n' + sender.username + ': ' + event.text + ' [' + str(chat_id) + ']'
name = hashlib.sha1(out.encode('utf-8')).hexdigest()
outdir = ECHODIR + '/' + str(chat_id)
f_h = open(outdir + '/' + name, 'a')
f_h.write(out)
f_h.close()
CLIENT.start()
CLIENT.run_until_disconnected()
how can I detect that an image is received and download the image from the event?
p.s. removed unnecessary code, e.g. to check if dir exist
As per the Objects Reference summary for Message, the message.photo property will be "The Photo media in this message, if any.".
This means that, to detect an image (or photo) in your code you can do:
if event.photo:
...
The Message methods also contains a message.download_media() such that:
saved_path = await event.download_media(optional_path)

discord.py - Send Messages on Specific Channel by Name

I want to make so when a message gets deleted, it sends the message that got deleted in #logs
CODE:
#bot.event
async def on_message_delete(message):
data = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("[" + (colored("{}".format(data), 'white')) + "][" +
(colored("{}".format(message.server), 'blue')) + " - " +
(colored("{}".format(message.channel), 'magenta')) + "] " +
(colored("{}".format(message.author), 'cyan', 'on_magenta') +
(colored(": {}".format(message.content), 'red'))))
channel = bot.get_channel("logs")
await bot.say(channel, "ALERT: Message Deleted")
await bot.say(channel, "Message {} got deleted by {} in {}".format(message.content, message.author, channel))
await bot.process_commands(message)

Python - open() isn't working

#BLACKLIST PROFILE CREATION COMMAND
#bot.command(pass_context=True)
async def blacklist(ctx, removeoradd, user: discord.Member, *, reason):
if ctx.message.author.id == developerID:
if removeoradd == "add":
case_id = "BL-" + id_generator(10, "1234567890")
blacklist_template = "{\"" + user.id + "\": {\"userid\": \"" + user.id + "\", \"reason\": \"" + reason + "\", \"banned_by\": \"" + ctx.message.author.id + "\", \"case_id\": \"" + case_id + "\", \"active\": \"True\"}}"
# with open("C:/Blacklisted/{}.json".format(ctx.message.author.id), "w") as json_file:
# json.dump(blacklist_template, json_file)
blacklist = open(os.path.expanduser("~/Blacklisted/{}.json".format(ctx.message.author.id)), "x")
blacklist.write("{}".format(blacklist_template))
blacklist.close()
embed = discord.Embed(title="Admin Control", description="Blacklisted:\n``{}/{}``".format(user.name, user.id))
embed.add_field(name="Reason", value=reason)
embed.add_field(name="Case ID", value=case_id)
embed.set_footer(text="v" + version + " | " + localtime)
await bot.say(embed=embed)
embed = discord.Embed(title="You can no longer create a profile.", description="If you think this is a mistake do {}appeal <reason>".format(prefix))
embed.add_field(name="Reason", value=reason)
embed.add_field(name="Case ID", value=case_id)
embed.set_footer(text="v" + version + " | " + localtime)
await bot.send_message(ctx.message.author, embed=embed)
elif removeoradd == "remove":
pass
else:
embed=discord.Embed(title="An error occured", description="Invalid argument.\nInsert ``add`` or ``remove``.", color=0xc20000)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="An error occured", description="No permission.\nYou need to be a verified developer to do this.", color=0xc20000)
await bot.say(embed=embed)
File "run.py", line 126, in blacklist
blacklist = open(os.path.expanduser("/Blacklisted/{}.json".format(ctx.message.author.id)), "x")
FileNotFoundError: [Errno 2] No such file or directory: '/Blacklisted/182288858782629888.json'
so basically im trying to create a file with the blacklist_template contents. I thought that when you use the "w" mode, it creates a new file for you. What am I doing wrong?

discord.py and private messages

I am trying to make discord-bot on phyton. Although I have understood discord API, I can't get the robot to send messages to members of server in private mail. Could you help me please
if message.content.startswith(myname + '!btcprice'):
print('[command]: btcprice ')
btc_price_usd, btc_price_rub = get_btc_price()
msg = 'USD: ' + str(btc_price_usd) + ' | RUB: ' + str(btc_price_rub)
await client.send_message(message.channel, msg)
I'm assuming you are calling this from the on_message event, in which case to send a PM you can get the member object from message.author. You can PM the user with this.
#client.event
async def on_message(message):
if message.content.startswith(myname + '!btcprice'):
print('[command]: btcprice ')
btc_price_usd, btc_price_rub = get_btc_price()
msg = 'USD: ' + str(btc_price_usd) + ' | RUB: ' + str(btc_price_rub)
await client.send_message(message.author, msg)

Identify sending user, Python IRC

So I made a Twitch.tv bot for my own channel, after having fun with it a little bit, I wanted to have some command restricted to some users, and some commands that can say the users name, for example:
Username reply example:
Person1: !tea
PythonBot: Would you like some tea, Person1?
Admin restriction example:
Person1: !ban Person2
PythonBot: I'm sorry, Person1, This command is restricted to admins only.
Ok, So here is the code I'm using (I will be modifying it soon to make it my own)
import socket
import threading
bot_owner = '~Not Today~'
nick = '~Not Today~'
channel = '~Not Today~'
server = 'irc.twitch.tv'
password = '~Not Today~'
queue = 13
irc = socket.socket()
irc.connect((server, 6667))
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
def message(msg):
global queue
queue = 5
if queue < 20:
irc.send('PRIVMSG' + channel + ' :' + msg + '\r\n')
else:
print 'Message Deleted'
def queuetimer():
global queue
queue = 0
threading.Timer(30,queuetimer).start()
queuetimer()
while True:
botdata = irc.recv(1204)
botuser = botdata.split(':')[1]
botuser = botuser.split('!')[0]
print botdata
if botdata.find('PING') != -1:
irc.send(botdata.replace('PING', 'PONG'))
if botdata.find('!res') != -1:
irc.send(botdata.replace('!res', '1600x900'))
The twitch IRC raw message is like
:jkm!jkm#jkm.tmi.twitch.tv PRIVMSG #trumpsc :needs Kappa
for above msg, it actually means userjkm at channel trumpsc saying needs Kappa
for your code, the method to get botuser is right, but you don't have the message the user sent, add following code should get the message
botmsg = botdata.split(':')[2]
so you get the message and username, the next step would be handling them.
Here would be some example for your need. For me, I will prepared a adminuserList and commmandList for other command, but I will simplify it here.
def commmanHandler(botuser, botmsg): # botmsg = '!ban user1'
command = botmsg.split(' ')[0] # command = '!ban'
command = command[1:] # command = 'ban'
argu = message.split(' ')[1] # argu = 'user1'
if command not in commmandList:
raise Exception("command not support")
if command == 'ban': # ban command, or using switch
# check if admin
if botuser not in adminList:
raise Exception("I'm sorry, " + botuser + ", This command is restricted to admins only.")
# admin, able to ban
irc.send('PRIVMSG' + channel + ' :' + '.ban ' + argu)
then call this function in your while loop to handle all message you get
try:
commmanHandler(botuser, botmsg)
except Exception, e:
print e
irc.send('PRIVMSG' + channel + ' :' + e)
here would be my solution, and also, don't forget to give the bot moderator privilege.

Categories