Send online photo with Telegram Messenger API with HTML mode - python

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

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)

Requesting a dictionary definition python | Discord bot

So I am trying to request a definition from oxford dictionary through their API and when the user type !define (users word) the bot returns the definition. I am having a few issues see the code below.
#client.command()
async def define(word_id):
app_id = '************'
app_key = '***********'
language = 'en'
url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' +
language + '/' + word_id.lower()
r = requests.get(url, headers={'app_id': app_id, 'app_key': app_key})
await client.say("The definition is " + ("text \n" + r.text))
The error I'm getting is as follows:
discord.errors.HTTPException: BAD REQUEST (status code: 400) + discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: BAD REQUEST (status code: 400)
Here is what they expect me to use:
import requests
import json
# TODO: replace with your own app_id and app_key
app_id = '****'
app_key = '******'
language = 'en'
word_id = 'Ace'
url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' +
language + '/' + word_id.lower()
r = requests.get(url, headers = {'app_id': app_id, 'app_key':
app_key})
print("code {}\n".format(r.status_code))
print("text \n" + r.text)
print("json \n" + json.dumps(r.json()))

Call rest api to push data to kinesis using python

I am a newbie in python and aws.I dont know much how to ask questions in stackoverflow.
Please do not block me.
I am trying to send a HTTP Post Request to put record into Amazon Kinesis Stream.
I have created a stream mystream in kinesis. I use method post.
I tried the following link to set up gateway api and it worked fine.
https://docs.aws.amazon.com/kinesis/latest/APIReference/API_CreateStream.html
I am trying to do it with python code using requests.
But i am getting the below mentioned error:
The following is my code:
import sys, os, base64, datetime, hashlib, hmac
import requests # pip install requests
# ************* REQUEST VALUES *************
method = 'POST'
service = 'kinesis'
host = 'kinesis.eu-west-1.amazonaws.com'
region = 'eu-west-1'
endpoint = 'https://kinesis.eu-west-1.amazonaws.com'
content_type = 'application/x-amz-json-1.1'
amz_target = 'Kinesis_20181114.PutRecord'
request_parameters = '{'
request_parameters += '"StreamName": mystream,'
request_parameters += '"Data": + base64.b64encode(test) + ,'
request_parameters += '"PartitionKey": 1234 '
request_parameters += '}'
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-
examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def getSignatureKey(key,datestamp,region,service):
kDate = sign(('AWS4' +key ).encode('utf-8'), datestamp)
kRegion = sign(kDate,region)
kService = sign(kRegion,service)
kSigning = sign(kService, 'aws4_request')
return kSigning
# Read AWS access key from env. variables or configuration file. Best
practice is NOT
# to embed credentials in code.
with open ('C:\\Users\\Connectm\\Desktop\\acesskeyid.txt') as f:
contents = f.read().split('\n')
access_key = contents[0]
secret_key = contents[1]
if access_key is None or secret_key is None:
print('No access key is available.')
sys.exit()
# Create a date for headers and the credential string
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_uri = '/'
canonical_querystring = ''
canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host +
'\n' + 'x-amz-date:' + amzdate + '\n' + 'x-amz-target:' + amz_target + '\n'
signed_headers = 'content-type;host;x-amz-date;x-amz-target'
payload_hash = hashlib.sha256(request_parameters).hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' +
canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers +
'\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' +
'aws4_request'
string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope +
'\n' + hashlib.sha256(canonical_request).hexdigest()
signing_key = getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' +
credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' +
'Signature=' + signature
print authorization_header;
headers = {'Content-Type':content_type,
'X-Amz-Date':amzdate,
'X-Amz-Target':amz_target,
'Authorization':authorization_header}
# ************* SEND THE REQUEST *************
print '\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++'
print 'Request URL = ' + endpoint
r = requests.post(endpoint, data=request_parameters, headers=headers)
print '\nRESPONSE++++++++++++++++++++++++++++++++++++'
print 'Response code: %d\n' % r.status_code
print r.text
The following error i am getting
AWS4-HMAC-SHA256 Credential=AKIAI5C357A6YSKQFXEA/20181114/eu-west-
1/kinesis/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-
target,
Signature=1d7d463e77beaf86930806812188180db9cc7cff082663ad547f647a9c6d545a
BEGIN REQUEST++++++++++++++++++++++++++++++++++++
Request URL = https://kinesis.eu-west-1.amazonaws.com
RESPONSE++++++++++++++++++++++++++++++++++++
Response code: 400
{"__type":"SerializationException"}
Please can someone explain me how i can rectify the above error?
Is the code connecting to the stream?Is there a problem regarding
serialization of data?
The fact that you're getting a SerializationException means your code is working to talk to kinesis but the data you're giving in test is likely not valid JSON.
That said:
I strongly recommend not doing the requests logic stuff yourself but use the software development kit (SDK) for AWS, called boto3.
import json
import boto3
kinesis = boto3.client("kinesis")
response = kinesis.put_record(
StreamName="my-fancy-kinesis-stream",
Data=json.dumps({
'example': 'payload',
'yay': 'data',
'hello': 'world'
}),
PartitionKey="AdjustAsNeeded"
)
print response
This will instantiate a kinesis client using the credentials on your machine (either via instance metadata or ~/.aws/config) or environment variables.
Then it takes a simple dictionary and dumps it into a JSON string for the data.
Lots to say on partition keys that you can find out here.
Also, check out boto3!

Search image on Google images with the new Custom Search API?

So, I am testing this piece of code :
import requests
import json
searchTerm = 'parrot'
startIndex = '0'
searchUrl = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + \
searchTerm + "&start=" + startIndex
r = requests.get(searchUrl)
response = r.content.decode('utf-8')
result = json.loads(response)
print(r)
print(result)
And the response is :
<Response [200]>
{'responseData': None, 'responseStatus': 403, 'responseDetails': 'This API is no longer available.'}
Seems that I am trying to use the old API and it is deprecated now. When I check on the Google Custom Search API I don't see any way to search straight on google images, is this even possible with the new API ?
It is possible, here is new API reference:
https://developers.google.com/custom-search/json-api/v1/reference/cse/list
import requests
import json
searchTerm = 'parrot'
startIndex = '1'
key = ' Your API key here. '
cx = ' Your CSE ID:USER here. '
searchUrl = "https://www.googleapis.com/customsearch/v1?q=" + \
searchTerm + "&start=" + startIndex + "&key=" + key + "&cx=" + cx + \
"&searchType=image"
r = requests.get(searchUrl)
response = r.content.decode('utf-8')
result = json.loads(response)
print(searchUrl)
print(r)
print(result)
That works fine, I just tried.

Twitter OAuth fails to validate my Python command line tool

I have spent hours in frustration and now I have this:
import requests, json, urllib
import time
import string, random
from hashlib import sha1
import hmac, binascii
def twitterIDGenerator(length):
toRet = ""
for i in range(0, length):
toRet = toRet + random.choice(string.hexdigits)
return toRet
def twitterSignatureGenerator(baseString, keyString):
hashed = hmac.new(keyString, baseString, sha1)
return binascii.b2a_base64(hashed.digest()).rstrip('\n')
OAUTH_CONSUMER_KEY = ''
OAUTH_NONCE = twitterIDGenerator(32)
OAUTH_SIGNATURE_METHOD = 'HMAC-SHA1'
OAUTH_TIMESTAMP = str(int(time.time()))
OAUTH_VERSION = '1.0'
# Get request token from Twitter
request_tokenURL = 'https://api.twitter.com/oauth/request_token'
request_tokenParameterString = ("oauth_consumer_key=" + OAUTH_CONSUMER_KEY +
"&oauth_nonce=" + OAUTH_NONCE + "&oauth_signature_method=" +
OAUTH_SIGNATURE_METHOD + "&oauth_timestamp=" + OAUTH_TIMESTAMP +
"&oauth_version=" + OAUTH_VERSION)
request_tokenSigBaseString = ("POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&" +
urllib.quote(request_tokenParameterString))
request_tokenSignature = twitterSignatureGenerator(request_tokenSigBaseString,
'[REDACTED consumer secret key]')
request_tokenHeaders = {'oauth_nonce': OAUTH_NONCE,
'oauth_callback': 'oob',
'oauth_signature_method': OAUTH_SIGNATURE_METHOD,
'oauth_timestamp': OAUTH_TIMESTAMP,
'oauth_consumer_key': OAUTH_CONSUMER_KEY,
'oauth_signature': urllib.quote(request_tokenSignature),
'oauth_version': OAUTH_VERSION}
request_tokenResponse = requests.post(request_tokenURL, headers=request_tokenHeaders)
print request_tokenResponse.text
So far, it is supposed to return a request_token so I can have my user go to the PIN website so I can get the access_token. But I just get "Failed to validate oauth signature and token" from Twitter.
A possible reason for this is wrong URL encoding. I see that Twitter needs RFC3986 encoding. Is there a way to do this in Python? If yes, should I do it only at the two locations I am currently using urllib.quote? Is my oauth_signature generated correctly?
The documentation is annoyingly convoluted.

Categories