how to identify and download images in telehton newMessage event? - python

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)

Related

Looping through guild members with discord.py

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())

Send online photo with Telegram Messenger API with HTML mode

I'm creating a bot for Telegram Messenger with Python.
I'm using the following function :
def telegram_bot_sendtexHTML(bot_message):
bot_token = 'token'
bot_chatID = 'id'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=HTML&text=' + bot_message
response = requests.get(send_text)
return response.json()
I have a list of images online (with URL link) I want to send using this function.
For example : https://media.wordpress.com/picture1.jpg
How can I insert this lik in my function in order to being able to send directly the picture (and not the link of the picture) ?
Use sendPhoto instead of the sendMessage method.
The required parameters are nicely described in the documentation.
I've altered your telegram_bot_sendtexHTML function to a telegram_bot_sendImage;
def telegram_bot_sendImage(caption, url):
bot_token = ''
bot_chatID = ''
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendPhoto?chat_id=' + bot_chatID + '&parse_mode=HTML&caption=' + caption + '&photo=' + url
response = requests.get(send_text)
return response.json()
telegram_bot_sendImage('Cool image!', 'http://placehold.it/200x200')

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.

Convert Data Pulled from Server To String

I have been working on a TwitchTV Python chat bot for a while now, but I'm still getting to grips with Python.
It may seem simple, but this has confused me so I decided I would ask:
I'm currently pulling messages from Twitch Chat using data = irc.recv
What I want to do is use the data pulled and turn it into a string, so that I can then check for capitals in the messages using str.isupper()
I've already tried a few ways;
data = irc.recv (4096)
msg = data()
capsTime = "30s"
str = msg
if str.isupper():
message("[-] Woah! Hold back on the caps! (Timeout " + capsTime + ")")
message("/timeout " + user + capsTime)
# variable "user" already defined
This is just one, that unfortunately didn't work.
EDIT:
This is my new code, It runs without error messages, but It doesn't function as I want it to;
while True:
data = irc.recv (4096)
user = data.split(':')[1]
user = user.split('!')[0]
caps = data.split(':')[0]
capsmsg = str(data)
print data
if data.find('PING') != -1:
irc.send('PONG ' + data.split()[1] + '\r\n')
if capsmsg.isupper():
message("[-] Woah! Hold back on the caps, " + user + "! (Timeout 30s)")
message("/timeout " + user + " 30s")
EDIT 2:
Expected output:
If a message is found in ALL caps, it will print this message and time the user out:
message("[-] Woah! Hold back on the caps, " + user + "! (Timeout 30s)")
Current output:
The bot does not pick the message up or run the scripted code.
Try this:
data = irc.recv (4096)
# msg = data()
capsTime = "30s"
mystr = repr(data)
if mystr.isupper():
message("[-] Woah! Hold back on the caps! (Timeout " + capsTime + ")")
message("/timeout " + user + capsTime)
# variable "user" already defined
Don't use reserved keyword.

Categories