Google Hangouts Chat bot to send DMs via incoming webhook? - python

Is it possible to set up this simple bot, using an incoming webhook, but send the message as a DM (not a #mention) to specific user(s)?
My guess is no. But then how could I achieve this?
Right now, the message is just sent into the room in which the bot was added and I can't see anything on DMs in the messaging docs.
You can currently achieve this very easily in Slack by setting up a so called bot user and using their chat.postMessage but I would like to do this in Google Hangouts Chat instead.
from httplib2 import Http
from json import dumps
#
# Hangouts Chat incoming webhook quickstart
#
def main():
url = '<INCOMING-WEBHOOK-URL>'
bot_message = {
'text' : 'Hello from Python script!'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()

As of now you would need their Space ID or webhook url in order to DM the user privately whether you use a webhook (like you did) or REST API. Unless you have this Space ID/Webhook you cannot message a user. One way of getting it, is to ask the user for their spaceID and store it. Either way, Google API hasn't given a way to retrieve a different Space ID then the current one you are talking inside of. This means, a bot can only message users its interacted with at some point.
The current Space ID value can be retrieved from the event JSON (event['space']['name']) and then using messages.create to send a new message to the user
service.spaces().messages().create( parent = spaceName, body = response).execute()
OR it can be retrieved from the url https://chat.google.com/dm/ --> space ID is here <---
Google has not released any way of generating your own spaceID for a specific user.
EDIT: In order to get the webhook url. See below:
then copy and paste the webhook url into your code above.
NOTICE: If you need, this webhook url can be manufactured using the usual url for google chat with their space ID as mentioned above and a key and access token in this format: https://chat.googleapis.com/v1/spaces/< space ID >/messages?key=A< key goes here > &token=< access token here >
For info on how to get a key and access token, read the documentation provided here: https://developers.google.com/identity/protocols/OAuth2

Related

How to send a image to sky biometry from my pc?

I’m trying to send a photo saved on my pc through the SkyBiometry API but it says error_message: MISSING_ARGUMENTS - access_token is missing and I don’t know how to fix it.
This is the code I used:
auth_headers = {
‘api_key’: ‘my_api_key’,
‘api_secret’: ‘my_api_secret’,
‘Content-Type’: ‘application/json’
}
url = ‘http://api.skybiometry.com/fc/faces/detect’
files = {
‘source’: open(r"C:\Users\Diego\OneDrive\Desktop\API\img\happy.png", “rb”)
}
data = {
‘timeout’: 60
}
response = requests.post(url, files=files, data=data, headers=auth_headers)
print(response.json())
You need to get an API key from SkyBiometry it sounds like. See section 1.1 below
https://skybiometry.com/documentation/
Every call to the API is required to be authorized, which basically means that you must sign up and obtain API access keys before accessing the service. Once that is done, you are ready to go coding.
SkyBiometry provides two ways for the client to authenticate himself:
*api_key and api_secret – by choosing this method every call to API must include api_key and api_secret. By using this fields we can map API call to the API user.
api_key and domain authentication – there are some situations when disclosing api_secret is not an option (like using java script client code or flash). Instead of disclosing api_secret, API user can choose domain authentication method. During the call there is no need to specify api_secret, instead user will be authenticated by calling domain, which will be compared to specified in user profile settings.

How to add a person into Google Group Chat using webhooks

I have a chat and I want to use webhooks to add people into it.
I have tried tagging a user that was not in the chat but that did not work
from httplib2 import Http
from json import dumps
print()
import os
os.system('clear')
#messageinput = input('Message: ')
#
# Hangouts Chat incoming webhook quickstart
#
amp = 1
while amp == 1:
def main():
url = 'https://chat.googleapis.com/v1/spaces/AAAAHDmEsoI/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=YpCZyYAzFiTmZhFgs_KLGv8A1qcNFlZLVcUMNkswMCo%3D'
bot_message = {
'text' : 'Hi <users/113438975428215985106>'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
os.system('clear')
print('Message sent as FBI Agent!')
amp = amp + 1
The code did not work to add people
from my experience, i can tell you webhooks are not designed for that, incoming webhook is designed to send messages simply without doing complicated codes, thats the goal from incoming webhook.
and if you read the Hangouts Webhook Docs, you must've seen this:
Incoming webhooks let you send asynchronous messages into Hangouts Chat from applications that aren't bots themselves. For example, you can configure a monitoring application to notify oncall personnel on Hangouts Chat when a server goes down. Incoming webhooks serve as a quick and easy way to integrate with existing workflows such as these without the overhead of writing entire bot applications.
So what you want is not sending a message, what you want is bigger than this, so i suggest using Hangouts API which might help you.
Configure the API, get the credentials, and read the docs ;)

How to send python output to telegram CHANNEL not to Group and gmail email group

Hi I have a program in python that generates results every one hour. The result can be of anything.This program will run in local machine or in the virtual private network.
I have two requirements
1. Send this python generated result to one telegram group [Group name "ourworld"](created by me) automatically without user intervention . (I have desktop telegram client running or web.telegram.org running in the same system)
Send this result to gmail group email ID.
what are the methods available to achieve this requirement .Is there any working code available to do this job .Please share the info and details.
Edit:
The Issue that i am facing :
1.created a Bot using BotFather.
2.Adding this Bot to my Group ,Here i get an error could not add an member So added the Bot as admin in the group
3.Token of the BOT noted down.
4. Trying to get ChatId
in this forum (https://web.telegram.org/#/im?p=g154513121) someone says number after p=g is the chartid ,In my case there is no
number it shows #testingname like this.
Using this approach trying to get the Chat ID https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/getme
so here 738909732 become a chat Id (in this case why we need seperate
call for the chart id)
here it is true as response coming! Here the chat id is the ID of the my "testingname" no chart id generated for the group.
6.Now packing the URL to see the response i am getting this error.
https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/sendMessage?chat_id=738909732&text=testing
the output if i run this in browser
{"ok":false,"error_code":400,"description":"Bad Request: chat not
found"} {"ok":false,"error_code":403,"description":"Forbidden: bot
can't send messages to bots"}
How to resolve this issue and make the BOT working .why i am not able to add BOT to my group that says error "Cant Add user"
How to make this telegram group working.
Note : Using BotFather BOT created
In case for sending message to telegram group the above method provided by bipin_s works where the chat_id = -xxxxxx is used.This is correct id followed by - symbol to be used.
For Posting message in the "telegram channel " a minor change needs to be done in the URL.The URL must be framed as below .
url = "https://api.telegram.org/botTokenID/sendMessage?chat_id=#yourChannelChatID&text=message"
Replace the TokenID with your BOT tokenID replace the yourChannelChatID with your channel chart id.Please note that the channel id is not negative id.
the code will look like this
import request
url = "https://api.telegram.org/botXyz:wwwwDFSJSJSAX/sendMessage?chat_id=#telechanneltesting&text=message"
requests.post(url)
Here the "message" as in the URL it will be posted in telegram channel.
How to get channel id ?
Go to https://web.telegram.org/#/im in browser ,after login now search your "channel".Now in the browser address bar you will one link like https://web.telegram.org/#/im?p=#llliopppppsssssr
p=#llliopppppsssssr after the equal symbol what comes is channel chat ID.
to send message to the telegram "group" without any user intervention , you require a telegram bot. create one using telegram bot-father. take a look at this link. also note the token while creating the bot. This method will work only for telegram Group .Telegram channel another method to be followed which MarxBabu answered below in his answers post.
import requests
# telegram url
url = "https://api.telegram.org/bot<Token>"
def send_mess(text):
params = {'chat_id':-xxxxxxx, 'text': text}
response = requests.post(url + 'sendMessage', data=params)
return response
send_mess(result_you_want_to_send)
to get the chat_id follow the steps mentioned here. note: group chat id's always starts with '-' . e.g. of group chat_id -356163873. A token and chat_id is only what you require to send message to telegram group.
for sending group emails you have to search more as i do not know much
I have it running on a Raspberry pi. You must look for botfather to get your telegram token.
import telepot
from telepot.loop import MessageLoop
telegram_token = 'xxxx:xxxxxx'
user = 4444444
bot = telepot.Bot(telegram_token)
bot.sendMessage(user, 'Hey!')
For configuring gmail I don't have something here right now...
You can send emails in python through SMTP or using the Mailgun Api
I personally prefer using Mailgun as it is easier to setup and sending an email is as easy as sending a post request to mailgun.
You can get the free version of the api and add your group email id to the sandbox (to avoid spam) and then use requests to post an email with the given api token

YouTube API without user OAuth process

I am trying to fetch captions from YouTube video using YouTube Data API (v3)
https://developers.google.com/youtube/v3/guides/implementation/captions
So, first I tried to retrieve a captions list using this url:
https://www.googleapis.com/youtube/v3/captions?part=snippet&videoId=KK9bwTlAvgo&key={My API KEY}
I could retrieve the caption id that I'd like to download (jEDP-pmNCIqoB8QGlXWQf4Rh3faalD_l) from the above link.
Then, I followed this instruction to download the caption:
https://developers.google.com/youtube/v3/docs/captions/download
However, even though I input the caption id and my api key correctly, it shows "Login Required" error.
I suppose I need OAuth authentication, but what I am trying to do is not related to my users's account, but simply downloading public caption data automatically.
My question is: Is there any way to process OAuth authentication just once to get an access token of my own YouTube account and then reuse it whenever I need it in my application?
I can't speak to the permissions needed for the captions API in particular, but in general, yes, you can OAuth to your app once using your own account and use the access and refresh tokens to make subsequent OAuth'd requests to the API. You can find the details of generating tokens here:
https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps#Obtaining_Access_Tokens
To perform the steps manually (fortunately, you only need to do this once):
If access has already been granted for an app, it needs to be removed so that new auth credentials can be established. Go to https://security.google.com/settings/security/permissions (while logged into your account) and remove access to the app. If the client ID or secret change (or you need to create one), find them at https://console.developers.google.com under API Manager.
To grant access and receive a temporary code, enter this URL in a browser:
https://accounts.google.com/o/oauth2/auth?
client_id=<client_id>&
redirect_uri=http://www.google.com&
scope=https://www.googleapis.com/auth/youtube.force-ssl&
response_type=code&
access_type=offline&
approval_prompt=force
Follow the prompt to grant access to the app.
This will redirect to google.com with a code parameter (e.g.,
https://www.google.com/?code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&gws_rd=ssl#). Save the code.
Send a POST request (e.g., via Postman Chrome plugin) to https://accounts.google.com/o/oauth2/token with the following in the request body:
code=<code>&
client_id=<client_id>&
client_secret=<client_secret>&
redirect_uri=http://www.google.com&
grant_type=authorization_code
The response will contain both an access token and refresh token. Save both, but particularly the refresh token (because the access token will expire in 1 hour).
You can then use the access token to send an OAuth'd request manually, following one of the options here, essentially:
curl -H "Authorization: Bearer ACCESS_TOKEN" https://www.googleapis.com/youtube/v3/captions/<id>
or
curl https://www.googleapis.com/youtube/v3/captions/<id>?access_token=ACCESS_TOKEN
(When I tried the second option for captions, however, I got the message: "The OAuth token was received in the query string, which this API forbids for response formats other than JSON or XML. If possible, try sending the OAuth token in the Authorization header instead.")
You can also use the refresh token in your code to create the credential needed when building your YouTube object. In Java, this looks like the following:
String clientId = <your client ID>
String clientSecret = <your client secret>
String refreshToken = <refresh token>
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken);
try {
credential.refreshToken();
} catch (IOException e) {
e.printStackTrace();
}
youtube = new YouTube.Builder(transport, jsonFactory, credential).build();
I imagine you can do something similar in Python with the API Client Libraries, although I haven't tried Python.

GAE Channel API - 400 Bad Request on disconnect

I'm working on a chat application using GAE's Channel API in Python.
I don't think I've set it up correctly. When I leave a page I get the following error message in my browser console:
http://localhost:8080/_ah/channel/dev?command=disconnect&channel=0e0acee3bd…122e0acaa86eeb-channel-1354440420-1452408747-mike|5066549580791808&client=1 400 (Bad Request)
Also, when I send chat message it sends duplicate messages, so I'm guessing users are not being properly disconnected.
I've set it up such that when user visits page, my backend code checks if they are logged in, and if so will automatically create token based on their username and the permalink ID of the page.
I then create a token, calling channel.create_channel method and pass that token as a value in the dict I include when I render my template (Jinja).
In my front-end I open the channel with the token. My on-close function is:
socket.onclose = function(){
connected = false;
}
In my app.yaml file I have included inbound_services: - channel presence.
In my backend code, I have '/_ah/channel/disconnected/'routed to a class that gets that permalink's entity instance, finds the client id from a list of connections and removes that connection from the entity.
Can you someone help me think about the Channel API the right way?

Categories

Resources