Can't push a notification in a pushbullet channel using the pushbullet API - push-notification

I've tried something like this:
from pushbullet import PushBullet
API_KEY = myAPIKey
pb = PushBullet(myAPIKey)
push = pb.push_note('Title', 'Desc', channel="myTag")
I've already created a channel (with the relative tag). This code produces the output
data["channel_tag"] = channel.channel_tag; AttributeError: 'str' object has no attribute 'channel_tag'
What am I doing wrong?

print(pb.channels)
push = pb.push_note('test', 'test', channel=pb.channels[channel_index])

Related

Calling a REST API using Azure function App and store data in Azure container

I have a requirement to call a rest api and store the resulting json in azure storage container. I have tried standalone python coding to extract the data from rest api and able to successfully receive the data from api that has pagination. Now I need to integrate/modify this python coding inside Azure Function and will ultimately store the resulting json data in a azure storage container. I am fairly new to Azure and hence need your guidance on how to tweak this code to suit in Azure function that will in turn push the json to azure container finally.
response = requests.post(base_url,
auth=(client_id, client_secret), data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret,'resource':resource})
acc_token_json = response.json()
access_token = json.loads(response.text)
token = access_token['access_token']
#call API to know total pages
API_Key = 'xxxxx'
api_url='https://api.example.com?pageSize=10&page=1&sortBy=orderid&sortDirection=asc'
headers = {
'Authorization': token,
'API-Key': API_Key,
}
r = requests.get(url=api_url, headers=headers).json()
total_record=int(r['pagination']['total'])
total_page=round(total_record/500)+1
#loop through all pages
all_items = []
for page in range(0, total_page):
url = "https://api.example.com?pageSize=500&sortBy=orderid&sortDirection=asc&page="+str(page)
response = requests.get(url=url, headers=headers).json()
response_data=response['data']
all_items.append(response_data)
Your inputs/guidances are very much appreciated.
You can put the logic in the body of the function.(Function is just set the condition of trigger.)
For example, if you are based on HttpTrigger:
import logging
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
'''
#Put the your logic code here.
'''
return func.HttpResponse(
"This is a test.",
status_code=200
)
And you can also use blob output to achieve your requirement, it is easier, have a look of this offcial doc:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-output?tabs=python#example
Let me know if have any problem.

How to emulate request parameters when running a Firebase client locally

I've got a Google Dialogflow application I'm putting together that has a number of fulillments I need to process with external REST apis. I've got the client set up and working with firebase serve, enabling me to test locally. My index.js functions have the following siganture:
exports.clientEmployeeServiceCodes = functions.https.onRequest(async (req, res)=>{...});
But when I run locally any request parameter I pass through the url comes up as undefined. Here is an example.
http://localhost:5000/arc-caregiver-f8ec9/us-central1/clientEmployeeServiceCodes?phone=%22%%2b12123003939%22
But I get params when I call through Dialogflow. So my question is whether I'm doing someting wrong or if there's a way to emulate those params in my url call so the method behaves just as it would if I called it from Dialogflow.
Here is the example where I am getting the Dialogflow parameters via the req object. Note where I get the value of pin.
exports.userHours = functions.https.onRequest(async (req, res)=>{
const start = MyUtils.getDatePlus(-14);
const end = MyUtils.getDatePlus(14);
var view = 'API_Pay_Periods';
var form = 'Pay_Periods';
var criteria = 'Pay_Period_Date >= "'+start+'" %26%26 Pay_Period_Date <=
"'+end+'"'
const ret = await callRestAPI(Config,view,form,criteria);
const pp = getPayPeriod(ret);
const pin = req.query.pin
console.log('pin',pin)
const data = await RESTAPI(Config, view,form,criteria);
res.status(200).send(response);
....
res.end();
});
Dialogflow sends its fulfillment information via a POST to your webhook with the JSON object in the body of the request. You cannot duplicate this by sending query parameters in the URL itself.
One typical way to work with this is to setup an ngrok tunnel to your local environment and use it to record the JSON body that is sent. You can then use this same body for testing later.

Can't yield json response from server with redux-saga

i am trying to use the stack react redux and redux-saga and understand the minimal needed plumbing.
i did a github repo to reproduce the error that i got :
https://github.com/kasra0/react-redux-saga-test.git
running the app : npm run app
url : http://localhost:3000/
the app consists of a simple combo box and a button.
Once selecting a value from the combo, clicking the button dispatch an action that consists simply of fetching some json data .
The server recieves the right request (based on the selected value) but at the line let json = yield call([res, 'json']). i got the error :
the error message that i got from the browser :
index.js:2177 uncaught at equipments at equipments
at takeEvery
at _callee
SyntaxError: Unexpected end of input
at runCallEffect (http://localhost:3000/static/js/bundle.js:59337:19)
at runEffect (http://localhost:3000/static/js/bundle.js:59259:648)
at next (http://localhost:3000/static/js/bundle.js:59139:9)
at currCb (http://localhost:3000/static/js/bundle.js:59212:7)
at <anonymous>
it comes from one of my sagas :
import {call,takeEvery,apply,take} from 'redux-saga/effects'
import action_types from '../redux/actions/action_types'
let process_equipments = function* (...args){
let {department} = args[0]
let fetch_url = `http://localhost:3001/equipments/${department}`
console.log('fetch url : ',fetch_url)
let res = yield call(fetch,fetch_url, {mode: 'no-cors'})
let json = yield call([res, 'json'])
// -> this is the line where something wrong happens
}
export function* equipments(){
yield takeEvery(action_types.EQUIPMENTS,process_equipments)
}
I did something wrong in the plumbing but i can't find where.
thanks a lot for your help !
Kasra
Just another way to call .json() without using call method.
let res = yield call(fetch,fetch_url, {mode: 'no-cors'})
// instead of const json = yield call([res, res.json]);
let json = yield res.json();
console.log(json)
From redux-saga viewpoint all code is slightly correct - two promises are been executed sequentially by call effect.
let res = yield call(fetch,fetch_url, {mode: 'no-cors'})
let json = yield call([res, 'json'])
But using fetch in no-cors mode meant than response body will not be available from program code, because request mode is opaque in this way: https://fetch.spec.whatwg.org/#http-fetch
If you want to fetch information from different origin, use cors mode with appropriate HTTP header like Access-Control-Allow-Origin, more information see here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Telegram Bot How to delete or remove a message or media from a channel or group

I want to know an example of removing message or file like a photo
I did not find any functional tutorial in this regard,
There is no such functionality in Telegram Bot API right now.
UPD 2017-05-19: There is an official method deleteMessage, more info:
https://core.telegram.org/bots/api#deletemessage
https://stackoverflow.com/a/43965602/1140438
There is an official support of deleteMessage method in Bot API 3.0. More details here:
https://core.telegram.org/bots/api#deletemessage
https://api.telegram.org/botTOKEN/deleteMessage?chat_id=CID&message_id=MID
As you can see there are two arguments: chat_id and message_id.
You can remove bot's messages or other messages (if bot is admin) except service messages (such as join/leave messages).
On success, it will return following JSON object:
{"ok":true,"result":true}.
If you are trying to remove service message or other user's message, but bot is not an admin:
{"ok":false,"error_code":400,"description":"Bad Request: message can't be deleted"}.
If you are trying to remove non-existent message or its already deleted:
{"ok":false,"error_code":400,"description":"Bad Request: message to delete not found"}
Kindly check with the below code snippet!, the below code have worked for me!
String chatId = String.valueOf(callbackQuery.getMessage().getChatId());
Integer messageId = callbackQuery.getMessage().getMessageId();
DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId);
try {
execute(deleteMessage);
}catch(TelegramApiException tae) {
throw new RuntimeException(tae);
}
you can forward message and save message id, and then remove that message. if you can do it, your message exist.
do it:
try:
mes=bot.forward_message(chat_id=?,from_chat_id=?,message_id=?)
bot.delete_message(chat_id=?,message_id=mes.id)
except:
print("your message deleted")
There are two methods in bot api that let you to edit a message: editMessageText and editMessageCaption. It is not ideal, but you can use it as an alternative.
For example by editing the message to:
"This message is unavailable."
Using python, if you have a CommandHandler() you can read the chat_id and message_id like so:
dispatcher.add_handler(CommandHandler("start", handler_start))
def handler_start(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
message_id = update.message._id_attrs[0]
context.bot.delete_message(chat_id, message_id)
If on php. I send message. Get response from it (message id of bot) And use deleteMessage
<?php
$botToken = "yourBotToken";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$update = json_decode(file_get_contents('php://input'), TRUE);
$msg = $update['message']['text'];
if ($msg == '/start') {
$data = http_build_query([
'text' => "test message (delete this)",
'chat_id' => $update['message']['chat']['id'],
]);
$send = file_get_contents($botAPI . "/sendMessage?{$data}");
$response = json_decode($send), true); // decode response
$message_id = $response['result']['message_id']; // get bots message
// Deleting message
$data_del = http_build_query([
'chat_id' => $update['message']['chat']['id'],
'message_id' => $message_id,
]);
file_get_contents($botAPI . "/deleteMessage?{$data_del}");
}
https://api.telegram.org/botTOKEN/deleteMessage?chat_id=CID&message_id=MID
Example
https://api.telegram.org/bot123456789:zzzzzzzzxxxxxxxxxxyyyyyyyyyy/deleteMessage?chat_id=123456789&message_id=123456,
It is important that the id of the message temine with a (comma) (,) and you can see it in the json when you send the message

How to use getUpdates after setWebhook in Telegram Bot API

I use setWebhook for my telegram-bot and now I need to use getUpdates. I have read the docs, and they say, that I can use only one method.
The problem is, that I have in console:
{"ok":false,"error_code":409,"description":"Error: Conflict: another webhook is active"}
So the question is, how to UNSET webhook and use getUpdates?
In a browser send the following request:
https://api.telegram.org/bot655390656:bhFS50...ff3zO4/setwebhook
as mentioned in Telegram bot api documentations you just need to pass empty string to url parameter.
> base_url = 'https://api.telegram.org/bot' + TOKEN + '/'
> data = {"url": ""}
> requests.post(base_url + 'setWebhook', data=data)
you can just call the method
deleteWebhook()
https://core.telegram.org/bots/api#deletewebhook
for example using telepot
import telepot
bot = telepot.Bot('YOUR_AUTHORIZATION_TOKEN')
bot.deleteWebhook()
I wrote a small rake task for this job
require 'net/https'
namespace :telegram_custom do
desc "Deactives webhook - this is needed to enable polling in development"
task deactivate_webhook: :environment do
token = "YOUR_BOT_TOKEN"
base_url = "https://api.telegram.org/bot#{token}/setwebhook"
uri = URI.parse(base_url)
res = Net::HTTP.get URI(base_url)
puts res
end
end
If you have the token stored in the credentials you can get them via: token = Rails.application.credentials.telegram[:bot]

Resources