How to send photo on telegram bot - python

i'm just implementing a simple bot who should send some photos and videos to my chat_id.
Well, i'm using python, this is the script
import sys
import time
import random
import datetime
import telepot
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Got command: %s' % command
if command == 'command1':
bot.sendMessage(chat_id, *******)
elif command == 'command2':
bot.sendMessage(chat_id, ******)
elif command == 'photo':
bot.sendPhoto(...)
bot = telepot.Bot('*** INSERT TOKEN ***')
bot.message_loop(handle)
print 'I am listening ...'
while 1:
time.sleep(10)
In the line bot.sendphoto I would insert the path and the chat_id of my image but nothing happens.
Where am I wrong?
thanks

If you have local image path:
bot.send_photo(chat_id, photo=open('path', 'rb'))
If you have url of image from internet:
bot.send_photo(chat_id, 'your URl')

Just using the Requests lib you can do it:
def send_photo(chat_id, file_opened):
method = "sendPhoto"
params = {'chat_id': chat_id}
files = {'photo': file_opened}
resp = requests.post(api_url + method, params, files=files)
return resp
send_photo(chat_id, open(file_path, 'rb'))

I have used the following command while using python-telegram-bot to send the image along with a caption:
context.bot.sendPhoto(chat_id=chat_id, photo=
"url_of_image", caption="This is the test photo caption")

I've tried also sending from python using requests. Maybe it's late answer, but leaving this here for others like me.. maybe it'll come to use..
I succeded with subprocess like so:
def send_image(botToken, imageFile, chat_id):
command = 'curl -s -X POST https://api.telegram.org/bot' + botToken + '/sendPhoto -F chat_id=' + chat_id + " -F photo=#" + imageFile
subprocess.call(command.split(' '))
return

This is complete code to send a photo in telegram:
import telepot
bot = telepot.Bot('______ YOUR TOKEN ________')
# here replace chat_id and test.jpg with real things
bot.sendPhoto(chat_id, photo=open('test.jpg', 'rb'))

You need to pass 2 params
bot.sendPhoto(chat_id, 'URL')

sendPhoto requires at least two parameters; first one is target chat_id, and for second one photo you have three options:
Pass file_id if the photo is already uploaded to telegram servers (recommended because you don't need to reupload it).
If the photo is uploaded somewhere else, pass the full http url and telegram will download it (max photo size is 5MB atm).
Post the file using multipart/form-data like you want to upload it via a browser (10MB max photo size this way).

Related

Telegram Bot receive video from user

i want my bot to receive videos thats been sent by users. Previously, i did this coding to receive images from users but i still cant use my bot to receive videos from them. Can any of you help me solve this problem?
coding:
file = update.message.photo[-1].file_id
At first place telegram can recieve two types of videos: simple videofile, that was sent by user as attachment and "video_note" - video that was created directly in the telegram.
Recieving both these types are pretty similar:
At first we need to obtain file_id:
def GetVideoNoteId(update):
if update['message'].get('video_note') != None:
return update['message']['video_note']['file_id']
else:
return 'not videonote'
second step - getting filepath of that file on telegram servers - from where we should download that file:
def GetVideoNoteFileSource(FileId):
url = 'https://api.telegram.org/bot' + TOKEN + '/' + 'getFile'
jsn = {'file_id': FileId}
r = requests.get(url,json=jsn).json()
fileSource = r['result']['file_path']
return fileSource
And third - finally - getting this file:
def GetFile(fileSource):
url = 'https://api.telegram.org/file/bot' + TOKEN + '/' + fileSource
r = requests.get(url)
filename = 'Video.mp4'
try:
with open(filename, 'wb') as file:
file.write(r.content)
return 'file dowloaded'
except:
return 'there are something wrong'
With videofile as attachments similar, but
return update['message']['video_note']['file_id'] - would be looks different (i do not remmember)

How to send file from server using telebot?

I made a bot that sends files from an external server with a URL.
I want the bot to send files directly from your server.
What am I doing wrong? Why didn't the open() command work?
import telebot
bot = telebot.TeleBot("Token")
#bot.message_handler(commands=['start','help'])
def send_start_message(message):
bot.reply_to(message, "Hi.")
#bot.message_handler(func=lambda m: True)
def echo_all(message):
print(message.text)
duck = open('duck.png','r')
bot.send_photo(message.chat.id, duck)
bot.send_message(message.chat.id, "hi")
bot.polling()
You'll need to tell python3 to use binary mode;
duck = open('duck.png', 'rb')
Read more about open()
Minimal working example to send local image:
import telebot
bot = telebot.TeleBot("<YOUR-TOKEN-HERE>")
cid = <YOUR-ID-HERE>
img = open('image.jpg', 'rb')
bot.send_photo(cid, img)

Connect to Watson Speech-to-Text API using websockets for real-time transcription

I am trying to write a script to call the Watson Speech-to-Text (STT) API to continually transcribe speech being recorded through a microphone word-for-word in real-time. I read that this should be possible using the Websockets version of the API.
I have a Python script that should be able to do this on Linux (assuming the dependencies are installed), however, it does not work on Mac OS X.
from ws4py.client.threadedclient import WebSocketClient
import base64, json, ssl, subprocess, threading, time
class SpeechToTextClient(WebSocketClient):
def __init__(self):
ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
username = "your username"
password = "your password"
auth_string = "%s:%s" % (username, password)
base64string = base64.encodestring(auth_string).replace("\n", "")
self.listening = False
try:
WebSocketClient.__init__(self, ws_url,
headers=[("Authorization", "Basic %s" % base64string)])
self.connect()
except: print "Failed to open WebSocket."
def opened(self):
self.send('{"action": "start", "content-type": "audio/l16;rate=16000"}')
self.stream_audio_thread = threading.Thread(target=self.stream_audio)
self.stream_audio_thread.start()
def received_message(self, message):
message = json.loads(str(message))
if "state" in message:
if message["state"] == "listening":
self.listening = True
print "Message received: " + str(message)
def stream_audio(self):
while not self.listening:
time.sleep(0.1)
reccmd = ["arecord", "-f", "S16_LE", "-r", "16000", "-t", "raw"]
p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)
while self.listening:
data = p.stdout.read(1024)
try: self.send(bytearray(data), binary=True)
except ssl.SSLError: pass
p.kill()
def close(self):
self.listening = False
self.stream_audio_thread.join()
WebSocketClient.close(self)
try:
stt_client = SpeechToTextClient()
raw_input()
finally:
stt_client.close()
Ideally, I wouldn't even be doing this in Python, but R, which is my native language which I will have to transfer the results back to to be processed anyway.
Could anyone provide me with a solution for how I can get a streamed transcription?
Not sure if this answer is exactly what you want, but sounds like an issue with the parameter continuous.
As you can see, has the lib Python SDK inside Watson-developer-cloud.
You can install with: pip install watson-developer-cloud
import json
from os.path import join, dirname
from watson_developer_cloud import SpeechToTextV1
speech_to_text = SpeechToTextV1(
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD',
x_watson_learning_opt_out=False
)
print(json.dumps(speech_to_text.models(), indent=2))
print(json.dumps(speech_to_text.get_model('en-US_BroadbandModel'), indent=2))
with open(join(dirname(__file__), '../resources/speech.wav'),
'rb') as audio_file:
data = json.dumps(speech_to_text.recognize(audio_file, content_type='audio/wav', timestamps=False, word_confidence=False, continuous=True), indent=2)
print(data)
Obs.: The service returns an array of results with one per utterance.
In the line #L44, has the params that you can use, so, for continuous transcription, you need to use the parameter continuous and set to true like the example above.
See the Official Documentation talking about Websockets for keeping the connection alive. (Maybe this is what you need).
For some good examples of how to do this using R, check out these great blog posts by Ryan Anderson.
Voice Controlled Music Machine
Python as a tool to help with Continuous Audio - This shows how you can use R for your main logic, and use Python to deal with handling just the audio.
Ryan has done a lot of work with R and the Watson API's - he shares a lot of his knowledge on his blog.

How to have Python post a file to Slack

I have a Python script that currently posts a link to a slack group chat. What can I change or add to make it drop a CSV file instead of dropping the link to take you to the CSV file. Thank you
def post_slack():
"""Post slack message."""
try:
token = 'token'
slack = Slacker(token)
obj = slack.chat.post_message(
channel='#dataworksapp',
text='https://console.cloud.google.com/storage/browser/firebase_results/?project=dataworks-356fa',
as_user=True,
attachments=[{"pretext": "Subject",
"text": "Body"}])
print obj.successful, obj.__dict__['body']['channel'], obj.__dict__[
'body']['ts']
except KeyError, ex:
print 'Environment variable %s not set.' % str(ex)
if __name__ == '__main__':
post_slack()
#post to slack above
The channels parameter is actually a string, not an array.
client.api_call('files.upload', filename='file.png', channels='#thechannel', file=open('/tmp/file.png','rb'))
You can also try this -
client.files_upload(channels='#thechannel', filename='file.png', file=open('/tmp/file.png', 'rb'))

Python: Upload a photo to photobucket

Can a Python script upload a photo to photo bucket and then retrieve the URL for it? Is so how?
I found a script at this link: http://www.democraticunderground.com/discuss/duboard.php?az=view_all&address=240x677
But I just found that confusing.
many thanks,
Phil
Yes, you can. Photobucket has a well-documented API, and someone wrote a wrapper around it.
Download the it and put it into your Python path, then download httplib2 (you can use easy_install or pip for this one).
Then, you have to request a key for the Photobucket API.
If you did everything right, you can write your script now. The Python wrapper is great, but is not documented at all which makes it very difficult to use it. I spent hours on understanding it (compare the question and response time here). As example, the script even has form/multipart support, but I had to read the code to find out how to use it. I had to prefix the filename with a #.
This library is a great example how you should NOT document your code!
I finally got it working, enjoy the script: (it even has oAuth handling!)
import pbapi
import webbrowser
import cPickle
import os
import re
import sys
from xml.etree import ElementTree
__author__ = "leoluk"
###############################################
## CONFIGURATION ##
###############################################
# File in which the oAuth token will be stored
TOKEN_FILE = "token.txt"
IMAGE_PATH = r"D:\Eigene Dateien\Bilder\SC\foo.png"
IMAGE_RECORD = {
"type": 'image',
"uploadfile": '#'+IMAGE_PATH,
"title": "My title", # <---
"description": "My description", # <---
}
ALBUM_NAME = None # default album if None
API_KEY = "149[..]"
API_SECRET = "528[...]"
###############################################
## SCRIPT ##
###############################################
api = pbapi.PbApi(API_KEY, API_SECRET)
api.pb_request.connection.cache = None
# Test if service online
api.reset().ping().post()
result = api.reset().ping().post().response_string
ET = ElementTree.fromstring(result)
if ET.find('status').text != 'OK':
sys.stderr.write("error: Ping failed \n"+result)
sys.exit(-1)
try:
# If there is already a saved oAuth token, no need for a new one
api.username, api.pb_request.oauth_token = cPickle.load(open(TOKEN_FILE))
except (ValueError, KeyError, IOError, TypeError):
# If error, there's no valid oAuth token
# Getting request token
api.reset().login().request().post().load_token_from_response()
# Requesting user permission (you have to login with your account)
webbrowser.open_new_tab(api.login_url)
raw_input("Press Enter when you finished access permission. ")
#Getting oAuth token
api.reset().login().access().post().load_token_from_response()
# This is needed for getting the right subdomain
infos = api.reset().album(api.username).url().get().response_string
ET = ElementTree.fromstring(infos)
if ET.find('status').text != 'OK':
# Remove the invalid oAuth
os.remove(TOKEN_FILE)
# This happend is user deletes the oAuth permission online
sys.stderr.write("error: Permission deleted. Please re-run.")
sys.exit(-1)
# Fresh values for username and subdomain
api.username = ET.find('content/username').text
api.set_subdomain(ET.find('content/subdomain/api').text)
# Default album name
if not ALBUM_NAME:
ALBUM_NAME = api.username
# Debug :-)
print "User: %s" % api.username
# Save the new, valid oAuth token
cPickle.dump((api.username, api.oauth_token), open(TOKEN_FILE, 'w'))
# Posting the image
result = (api.reset().album(ALBUM_NAME).
upload(IMAGE_RECORD).post().response_string)
ET = ElementTree.fromstring(result)
if ET.find('status').text != 'OK':
sys.stderr.write("error: File upload failed \n"+result)
sys.exit(-1)
# Now, as an example what you could do now, open the image in the browser
webbrowser.open_new_tab(ET.find('content/browseurl').text)
Use the python API by Ron White that was written to do just this

Categories

Resources