Sending python computed values to telegram - python-3.7

I just created a telegram bot in python and I want to be sending the results of the data I analyse in python to a telegram channel in a special format, here is an sample of what I would like to send:
a = '#N' + game_to_analyse['Id_number'] + ': ' +'54783355882'
But when I try to send this value 'a' to my telegram channel, I only get " as message on my phone or telegram desktop app.
What is the issue?

The # is probably messing with your url
Solution:
urlencode() the query params:
from urllib.parse import urlencode, quote_plus
data = {
'text' : '#N12345:6789',
'chat_id': myChatId,
'parse_mode' : 'MarkDown'
}
encodedData = urlencode(data, quote_via=quote_plus)
url = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?' + encodedData
response = requests.get(url)

Related

Can't send a document via Telegram API on Swift; using Vapor

Code
let handler16 = TGMessageHandler(filters: .regexp(pattern: "^11$")) {update, bot in
if let id = update.message?.chat.id {
let chatId: TGChatId = .chat(id)
// let file = File(data: "hello", filename: "МЭСК.docx")
let params: TGSendDocumentParams = .init(chatId: chatId, document: .url("http://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE46130&format=file"))
try bot.sendDocument(params: params)
}
}
Error
Type: server Description: Response marked as not Ok, it seems something wrong with request
Code: 400
Bad Request: failed to get HTTP URL contentReason:
How can i save my particular document and send it (if it is big) via Telegram Bot ?
After that I'm running on linux server, i don't know how to do it correct...
If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this FileInfo.fileId("file_id") as a parameter instead of uploading. There are no limits for files sent this way.

How to generate Digest password on Dart for communicate with ip camera

I am trying to communicate with ip camera supporting the Onvif protocol and
I need to generate a Digest password.
Here's similar topic but it's didn't help.
Here's oasis-open standart for this thing.
If I understand correctly I should use this formula
Digest = B64ENCODE( SHA1( B64DECODE( Nonce ) + Date + Password ) )
I tried something like this:
import 'package:crypto/crypto.dart';
var username = "admin";
var mNonce = base64Encode(utf8.encode("12345678901234567890"));
Digest digest = sha1.convert(utf8.encode(mNonce + -12-25T07:55:35Z' + '21063598'));
var mPasswordDigest = base64Encode(digest.bytes);
But the ip camera response: 400 "not Authorized"
I used http sniffer and check what send worked app (Onvifer on Android),
I send the same copied request and it gives ok status code 200.
So the problem is incorrect way of digestPassword generation.
This is a body of a working request:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" '
'xmlns:c="http://www.w3.org/2003/05/soap-encoding" xmlns:v="http://www.w3.org/2003/05/soap-envelope">'
'<v:Header><Action mustUnderstand="1" xmlns="http://www.w3.org/2005/08/addressing">http://www.onvif.org/ver10/media/wsdl/GetSnapshotUri</Action>'
'<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><UsernameToken><Username>admin</Username>'
'<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">'
''x8IytKlr8cTH+sT9EzEaVDLqYGw='</Password>'
'<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">'
''Njg2YzYxZDI4YjA4ZDA0Nw=='</Nonce><Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">'
''2019-12-25T07:55:35Z'</Created></UsernameToken></Security></v:Header><v:Body><GetSnapshotUri xmlns="http://www.onvif.org/ver10/media/wsdl">'
'<ProfileToken>PROFILE_000</ProfileToken></GetSnapshotUri></v:Body></v:Envelope>';
We need to generate use this formula
Digest = B64ENCODE( SHA1( Nonce + Date + Password ) )
import 'package:crypto/crypto.dart';
var username = "admin";
var mNonce = base64Encode(utf8.encode("12345678901234567890"));
Digest digest = sha1.convert(utf8.encode("12345678901234567890"+ -12-25T07:55:35Z' + '21063598'));
var mPasswordDigest = base64Encode(digest.bytes);

How to insert an emoji into an email sent with GmailApp?

I have a GAS script that sends automated emails and would like to include a couple of emojis. I've tried using shortcodes and copying/pasting, but nothing so far seems to have worked. Just wanted to see if there was anything I was missing.
Edit: Here's the code:
var title = rowData.publicationTitle;
var journal = rowData.journalTitle;
var url = rowData.publicationUrl;
//Emoji goes here in the body:
var body = "Hi " + firstName + "!<br><br>I noticed your article <a href='" + url + "'>“" + title + "”</a> was recently published in <i>" + journal + "</i>. Congratulations! This is just a friendly reminder to please upload your original document and a PDF version to our publications app when you have time.<br><br>To upload your publication, you can <a href='http://support.cpes.vt.edu/publishing'>click here</a>.<br><br>Thanks!<br><br>🤖 CB<br><br><hr style='background-color: #d8d8d8; border: 0 none; color: #d8d8d8; height: 1px;'><span style='font-size:12px'><b>CPES Publications Reminders</b> | <a href='mailto:leshutt#vt.edu' style='text-decoration:none'>Feedback</a> | <a href='http://support.cpes.vt.edu/publishing' style='text-decoration:none;'>Publication uploads</a></span>";
var emailSubject = "Just a reminder to upload your article!";
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
if (emailStatus == "Pending" && emailData !== "No emails found") {
GmailApp.sendEmail(email, emailSubject, body, {
from: aliases[2],
name: "CPES Bot",
htmlBody: body
});
}
I've noticed that sending a star ("⭐") works, but the normal smiley ("😊") shows up as a black-and-white, Unicode-esque icon and everything else I've tried are question marks. Can you only use emojis up to a certain Unicode release?
You want to send an email with HTML body including the emoji. If my understanding is correct, how about this modification?
About GmailApp and MailApp :
Unfortunately, GmailApp cannot use the recent emoji characters. At GmailApp
emoji less than Unicode 5.2 can be used for this situation.
emoji more than Unicode 6.0 can NOT be used for this situation.
MailApp can use all versions of emoji.
"⭐" is Unicode 5.1. But "😊" is Unicode 6.0. By this, in your script using GmailApp, you can see the former, but you cannot see the latter. At a sample script of Michele Pisani, the latter is sent using MailApp. So the character is not broken. "🤖" is Unicode 8.0.
Modification points :
So in the case of your script, the modification points are as follows.
Use MailApp instead of GmailApp.
OR
Use Gmail API.
From your comments to Michele Pisani, I worry about that MailApp might not work for your situation. So I would like to also propose the method using Gmail API.
1. Modified your script
Please modify as follows.
From :
GmailApp.sendEmail(email, emailSubject, body, {
To :
MailApp.sendEmail(email, emailSubject, body, {
2. Using Gmail API
In order to use this, please enable Gmail API at Advanced Google Services and API console as follows.
Enable Gmail API v1 at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Gmail API v1
Enable Gmail API at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "Gmail". And click Gmail API.
Click Enable button.
If API has already been enabled, please don't turn off.
If now you are opening the script editor with the script for using Gmail API, you can enable Gmail API for the project by accessing this URL https://console.cloud.google.com/apis/api/gmail.googleapis.com/overview
Sample script :
function convert(email, aliase, emailSubject, body) {
body = Utilities.base64Encode(body, Utilities.Charset.UTF_8);
var boundary = "boundaryboundary";
var mailData = [
"MIME-Version: 1.0",
"To: " + email,
"From: CPES Bot <" + aliase + ">",
"Subject: " + emailSubject,
"Content-Type: multipart/alternative; boundary=" + boundary,
"",
"--" + boundary,
"Content-Type: text/plain; charset=UTF-8",
"",
body,
"",
"--" + boundary,
"Content-Type: text/html; charset=UTF-8",
"Content-Transfer-Encoding: base64",
"",
body,
"",
"--" + boundary,
].join("\r\n");
return Utilities.base64EncodeWebSafe(mailData);
}
function myFunction() {
// Please declare email and firstName.
var title = rowData.publicationTitle;
var journal = rowData.journalTitle;
var url = rowData.publicationUrl;
//Emoji goes here in the body:
var body = "Hi " + firstName + "!<br><br>I noticed your article <a href='" + url + "'>“" + title + "”</a> was recently published in <i>" + journal + "</i>. Congratulations! This is just a friendly reminder to please upload your original document and a PDF version to our publications app when you have time.<br><br>To upload your publication, you can <a href='http://support.cpes.vt.edu/publishing'>click here</a>.<br><br>Thanks!<br><br>🤖 CB<br><br><hr style='background-color: #d8d8d8; border: 0 none; color: #d8d8d8; height: 1px;'><span style='font-size:12px'><b>CPES Publications Reminders</b> | <a href='mailto:leshutt#vt.edu' style='text-decoration:none'>Feedback</a> | <a href='http://support.cpes.vt.edu/publishing' style='text-decoration:none;'>Publication uploads</a></span>";
var emailSubject = "Just a reminder to upload your article!";
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
if (emailStatus == "Pending" && emailData !== "No emails found"){
// Added script
var raw = convert(email, aliases[2], emailSubject, body);
Gmail.Users.Messages.send({raw: raw}, "me");
}
}
Note :
When you use this sample, Please declare email and firstName.
Please run myFunction().
References :
Emojipedia
Advanced Google Services
Gmail API
If I misunderstand your question, I'm sorry.
I tried to copy the emoji (https://www.emojicopy.com/) and paste it directly into the script editor:
and after sending the email I received it in my mailbox:
Edit:
Be careful that some emoji are one character length (like the star) but other are 2 characters (like the smile) for those with 2 characters you can think of writing immediately after the smile but instead you are writing inside the smile so you break it therefore turns in question mark.
If you try to run this code, you will see that the first has length 2 and the second one has length 1:
If you try to move the pointer (in the apps script editor) on those 2 emoticons, from before to after the emoticon, you will see that in the case of the star just one step but for the smile you need 2 steps.
The easiest complete answer that also works with SMS recipients is this:
function testNewMail() {
MailApp.sendEmail({
to: "yourphonenumbergoeshere#mymetropcs.com",
subject: "Logos",
htmlBody: "😊 hi todd happy day"
});
}
Use code points (💎) in the value of your cell and send your message as HTML:
var sheet = SpreadsheetApp.getActiveSheet();
var value = sheet.getRange("A1").getValue();
GmailApp.sendEmail(
"recipient#example.com",
"subject",
"",
{
from: "sender#example.com",
htmlBody: value
}
);

Azure encoding job via REST Fails

I am trying to upload a video and encode it via azure rest service.
I have now hit the step of encoding the video but I am having difficulties with the request.
The following code shows my request:
var joburl = res.RequestMessage.RequestUri + "Jobs";
client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("x-ms-version", "2.8");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("x-ms-date", date);
//accept
t = new NameValueHeaderValue("odata", "verbose");
type = new MediaTypeWithQualityHeaderValue("application/json");
type.Parameters.Add(t);
client.DefaultRequestHeaders.Accept.Add(type);
result = await client.PostAsync(joburl,json);
the url:https://wamsamsclus001rest-hs.cloudapp.net/api/Jobs
the json:
{"Name":"khgfiuydencodingjob","InputMediaAssets":[{"__metadata":{"Uri":"https://wamsamsclus001rest-hs.cloudapp.net/api/Assets('nb%3acid%3aUUID%3ad037b321-cd1c-43a9-9607-c4910fa7a85b')"}}],"Tasks":[{"Configuration":"H264 Adaptive Bitrate MP4 Set 720p","MediaProcessorId":"nb:mpid:UUID:1b1da727-93ae-4e46-a8a1-268828765609","TaskBody":"<?xml version=\"1.0\"encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"}]}
The bearer token works as I use it for other request.
But I get a bad request 400 with the followin error message:
{"error":{"code":"","message":{"lang":"en-US","value":"Parsing request content failed due to: Make sure to only use property names that are defined by the type"}}}
Can anyone spot the error.
Thank you for the help
Okay I got it to work. Needed a odata=verbose in my json/string content - like this:
var jobInJson = JsonConvert.SerializeObject(job);
json = new StringContent(jobInJson, Encoding.UTF8);//,
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
I tried this earlier however I got a error 500 but now it is working.

samsung smart tv upload file

On the samsung dforum I found the URL which explains a function startUpload().
but also in forums i found people saying that uploading files by any means is not possible. If so why samsung provide the startUpload() function?
Did anybody tried file upload? please help
Documentation is incorrect. I tested it on UE46ES8000 and successfully uploaded file from USB flash drive connected to TV.
OnComplete callback called instead of OnUploadComplete.
To the end of uploaded data appended string --END_OF_PART--. If you strip it from file, you get your original file.
function OnUploadComplete (msg) {
alert('***OnUploadComplete***' + msg );
}
function OnUploadProgress (msg) {
alert('***OnUploadProgress***' + msg );
}
function fnDnStatus (msg) {
alert('fnCallback' + msg );
var tArrResult = msg.split("?");
for (var i=0; i < tArrResult.length; i++) {
alert("tArrResult[" + i + "] = " + tArrResult[i]);
}
// DownResult: If res=1 success, otherwise ERROR (see end of this file)
}
var DownloadPlugin = document.getElementById("pluginObjectDownload");
DownloadPlugin.OnUploadComplete = OnUploadComplete;
DownloadPlugin.OnUploadProgress = OnUploadProgress;
DownloadPlugin.OnComplete = fnDnStatus;
var sever = '192.168.137.1',
port = 80,
header = 'Header-name: Header value',
body = '[[[FILE_BINARY]]]',
filePath = '$USB_DIR/sda1/textfile.txt',
uploadRatio = '10',
serverType = 1;
DownloadPlugin.StartUpload(sever, port, header, body, filePath, uploadRatio, serverType);
I don't know meaning of header parameter. And I don't know how to specify url other than server root. Data was sent by POST request to http://192.168.137.1:80/.
At server side I saved it with simple script (http://192.168.137.1:80/index.php):
<?php
$t = file_get_contents('php://input');
if(strlen($t) > 1){
echo 'some data arrived';
}
file_put_contents('input.txt', $t);
?>
I just uploaded a video file to my Samsung uhd, through smartthings. Hold-Click on video. Tap share. Send to device. When it's done you will see video just shared in upper right corner. Click on watch video. I'm watching it now but cant figure out where its stored on the tv