How to send request to Telegram bot API? - api

After creating a telegram bot and gain bot token, I want to send a request to the bot API.
This link says we must send the HTTP request like this:
https://api.telegram.org/bot<token>/METHOD_NAME and brings example for easiest method "getme" which has not any input parameters.
Imagine I want to send some messages. I should use the sendMessage method which has two Required input parameters: chat_ID and text.
Now my Questions begins:
How can I write this sendMessage method in above request format with its parameters? I tried sendMessage(param1,param2) and received method not found message.
What is chat_id? if I want to send a message to the contact, how can I know his chat_id?
I searched a lot on the internet, there are plenty of projects on GitHub especially for this purpose, and honestly none of them makes any sense.
for god's sake someone please help me. I am loosing way.
Regards.

You just send a POST request to:
https://api.telegram.org/bot{token}/{method}
For example:
https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/sendMessage
In the body of the request, you URL encode the parameters:
chat_id=12345&text=hello%20friend
For example, in Python using the requests module:
import requests
response = requests.post(
url='https://api.telegram.org/bot{0}/{1}'.format(token, method),
data={'chat_id': 12345, 'text': 'hello friend'}
).json()
When a user chats with your bot, you get a Message object that has a chat id (and a user id, which you can substitute for a chat id). There's no way to initiate a chat with a user unless you already know their user id, so you have to wait for a user to talk to you. You can simplify that by using deep linking and having the user click on a link that sends a pre-made message when they hit the Start button.
Edit: for those struggling to find chat_id, here's a way:
1.- Create a bot: on Telegram's search look for #BotFather. Click start, write /newbot, give it a name and a username. You should get a token to access the HTTP API. Save this token.
2.- Find your bot on Telegram with its username. Write something to it e.g. 'test'. This will come in handy later.
3.- Print chat_id. Before running this function, make sure that you have at least written one message to your bot on Telegram (step 2)
Javascript code:
var token = "123456:kioASDdjicOljd_ijsdf"; // Fill this in with your token
var telegramUrl = "https://api.telegram.org/bot" + token;
function getChat_id(){
var res = UrlFetchApp.fetch(telegramUrl+"/getUpdates").getContentText();
var res = JSON.parse(res);
Logger.log(res.result[0].message.chat.id.toString());
}

Try this
https://api.telegram.org/bot{token}/sendMessage?chat_id=<chat_id>&text=<Enter your text here>
Example
https://api.telegram.org/bot449123456:AAHSAnSGDm8PW2Z-1ZiwdVDmgv7sM3NMTxg/sendMessage?chat_id=311911234&text=Hi+Everyone

Related

How to post a message to Slack via user token and Slack API

Is it possible to send a message via Slack API from my current user? I've created a slack user token, documentation also said:
User tokens represent the same access a user has to a workspace -- the channels, conversations, users, reactions, etc. they can see
Write actions with user tokens are performed as if by the user themselves
but when I'm trying to send some requests via Slack API, I get notified that I have no ops for it, example:
-> GET https://slack.com/api/users.identity (+ bearer with my user token)
->
{
"ok": false,
"error": "missing_scope",
"needed": "identity.basic",
"provided": "identify,app_configurations:read,app_configurations:write"
}
Same when I'm trying to send a message / get a conversations list
If all you want is to send a message then make sure to add the chat:write scope to your app from your OAuth & Permissions page on your app's management site. Remove all the other scopes, save an re-install your app. You should then be able to send a message using the chat.postMessage method. If you want to use the conversations.list method then you'll need to add the channels:read scope. To use the users.identity method you will need to enable Sign In with Slack as outlined here.

How to use the watchlist ID to access messages via the Stocktwits API?

I am trying to write a python script that collects messages from Stocktwits.
I managed to successfully access the API, with
params = {
'client_id':'my_consumer_key_here',
'response_type':'code',
'redirect_uri':'https://api.stocktwits.com/api/2/oauth/authorize',
'scope':['read','watch_lists'],
'prompt':1,
}
r = requests.get('https://api.stocktwits.com/api/2/oauth/authorize',params)
r.status_code # 200
The messages should be accessed via a watchlist (which I created on my account), like this
r = requests.get('https://api.stocktwits.com/api/2/streams/watchlist/<watchlist_id>.json',params)
To get at the watchlist-id, which I couldn't find on my account, I tried:
r = requests.get('https://api.stocktwits.com/api/2/watchlists.json',params)
r.status_code # 401
This should list the watchlists and their IDs. The '401' indicates that authorization for some reason doesn't work here the same way as above.
I changed the redirect_uri to 'https://api.stocktwits.com/api/2/watchlists.json' as well, frankly I'm not sure what it's good for.
The problem is likely that the authorization process is geared towards having many possible users accessing my app and via my app the API. What I want to do is much simpler.
I have never worked with an API before and most of the documentation is pretty opaque to me. So my question is whether I'm doing something obviously wrong and how I should proceed to get the watchlist_id and retrieve the messages.
You should add access token to your requests for secured resources like
https://api.stocktwits.com/api/2/streams/watchlists.json?access_token=<access_token>
or instead of this you can add authorization header to each request to protected resources.
And access_token you should get from your authorize request
r = requests.get('https://api.stocktwits.com/api/2/oauth/authorize',params)

How can a webhook identify USER_IDs?

I'm developing a webhook, and I want it to be able to #mention specific users. The simple message format specifies using the format of <users/123456789012345> to #mention a specific users. Since this is not a bot, it is not processing an incoming message and cannot pull the from the sender field, as suggested in the note on the developer site linked above.
How can I get the USER_ID of a user on my domain?
I am in the same boat as you. Trying to use a Webhook to mention a user.
If you inspect the HTML on https://chat.google.com, using web/dev tools, you can actually see user ID under tag data-member-id="user/bot/123456789012345"
Using the above I tried to form a webhook that mentioned the user (in my case another bot).
Unfortunately it didn't work. Passing in the string <users/123456789012345> please test came through to chat as a string literal.
It's strange because the html links and markup DO get interpreted. As mentioned here. Edit: so does <users/all>.
I'm leaving this here since your question asks for how to elicit the ID. While it may not be pretty, or much automatable, it helped me get the user ID at least.
Edit 2: It works, just not to mention my other bot for some reason. But using this method I was able to mention a human user :)
I use this for find the USER_ID but if you have another way let me know
Right click on the user and select inspect
Search for data-member-id this is your USER_ID
A webhook will not be able to pull the USER_ID of a user. As a workaround for this, you can create a service account and a bot that has access to the room and use the REST API spaces.members.list() and spaces.members.get() method.
Note: The bot will need to be added to the room.
Okay, so in order to get the UserID without having to do all of the things that you're trying to do here you need to use the Admin SDK API in google app script. Basically what you'll want to do is use your google app script as an intermediary for what you're trying to do. So you'll post something to google app script via their web exec functions on a deployed app and then have that app communicate to the google chat API via something like this:
var googlewebhookurl = 'https://chat.googleapis.com/v1/spaces/ASDFLKAJHEPQIHEWFQOEWNQWEFOINQ';
var options = {
'method': 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({ text: "<users/000000000001> I see you!" })
}
UrlFetchApp.fetch(googlewebhookurl, options);
To start, you'll need to add the Admin SDK API to the services in your google app script services area. So click the plus next to "Services" and then select the Admin SDK API and click add to add it to the services, it winds up showing up in the list as "AdminDirectory" once it has been added to the services.
This is an image showing what it looks like once you've added it to the services.
Here is a link to the documentation for the Admin SDK API getting user information: https://developers.google.com/apps-script/advanced/admin-sdk-directory#get_user
You should be able to copy and paste that example function to get the information you're looking for regarding the user. I'm pasting the example code below in case something happens to this link:
/**
* Get a user by their email address and logs all of their data as a JSON string.
*/
function getUser() {
var userEmail = 'liz#example.com';
var user = AdminDirectory.Users.get(userEmail);
Logger.log('User data:\n %s', JSON.stringify(user, null, 2));
}
In order to get the user id, take the user variable that comes back and access user.id and voila! You have the ID you're looking for. From there just plaster it into a text message in google chat and you should be in business. I haven't gotten it to work with cards at all yet. I'm not seeing any documentation saying that it's supported in cards at all. For more information regarding chat messages and cards take a look at these:
https://developers.google.com/chat/api/guides/message-formats/basic
https://developers.google.com/chat/api/guides/message-formats/cards

How to specify and implement Telegram API methods in Requests?

I am trying simply connect to Telegram API servers and get response.
I've create a app in my.telegram.org, Now I have my api_id, api_hash and also IP address to Telegram api MTproto serever. for getting start documentation says we have to Authorize first using auth.sendCode method to send a code to api user's phone.
so I tried this python script to use auth.sendCode method:
q="auth.sendCode \"phone_number\" 0 api_id \"api_hash\" \"en\""
res = requests.post("http://149.154.167.50:443",data=q)
and when I print res, it says Response [404]. according to the documentation it means An attempt to invoke a non-existent object, such as a method.
I am sure the problem is about my data field in post request. the string I made for calling auth.sendCode method is wrong so server can't recognize what I am trying to reach to.
there is a Query example for that method in documentation :
(auth.sendCode "79991234567" 1 32 "test-hash" "en")
please someone helps me to correct that data string (according to this example). how can I implement API methods in Post Requests?
First steps: Understand how to generate a Telegram AuthKey.
That exercise will help you build up the the basic knowledge need to move tackle Telegram API (and the rest API documentation) on your own.
For starters, i have outlined some of the basics in this SO Post (using vb.net)

Coinbase address callbacks not working?

I'm using the Coinbase API. My app generates new receive addresses with callbacks. However, when BTC arrives at any of those addresses, the callbacks don't seem to be firing.
I've verified that the callbacks are indeed being created for the new addresses, and that my app would respond correctly to the callbacks. For instance, this triggers the desired functionality on my server:
curl --data "address=someaddress&amount=1.2" https://mydomain.com/callback?secret_token=mysecret
Alas, there are no calls being made to my server whatsoever (any call would show up in the logs, but none do).
Anyone using Coinbase address callbacks successfully? Any hints for debugging this?
Have you tried using a json request with php to set the callback url? If you login and look at the addresses section, do you see the correct url in the callback section? Make sure there is no typo. I was able to do this a few months ago but have left the project that did this.
create a php file callback.php
put this code in your callback.php
<?php
$jsonData = file_get_contents('php://input');
$postDatacoinbase = json_decode($jsonData, true);
print_r ($postDatacoinbase);
?>
login into Coinbase and click on " Merchant settings " and
input your http://mydomain.com/callback.php url into callback url
and click test now to see the results .