Skip to content

Instantly share code, notes, and snippets.

@isnot
Created July 1, 2018 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isnot/6f03f85fbe2bd4d7d330bd593d5ae965 to your computer and use it in GitHub Desktop.
Save isnot/6f03f85fbe2bd4d7d330bd593d5ae965 to your computer and use it in GitHub Desktop.
テスト目標 Telegram Bot APIと、node.js+requestモジュール使用して。画像を送信(multipart/form-data)したい
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const request = require('request');
const config = {
'bot_api_key' : '356700597:AAAAAA',
'chat_id' : '-1001119217627',
'telegram_api_endpoint_prefix': 'https://api.telegram.org/bot',
'disable_web_page_preview' : 'true',
'parse_mode' : 'HTML',
'debug_mode' : true,
};
const path = '20050828_tokyogeosite4_.jpg';
const image = fs.readFileSync(path);
// テスト目標 Telegram Bot APIと、node.js+requestモジュール使用して。画像を送信(multipart/form-data)したい
console.log(new Date() + ' START /////////////////////////////////////////////////////////////');
sendMessage('its you!');// ok
console.log(path, image instanceof Buffer ? 'Buffer' : 'unknown type');
sendPhoto(path, image, 3153);// ng
// ここまでテスト 以下はテストしたい関数
// Telegramへ送信
function sendMessage(text) {
if (!text) {
return;// new Promise((resolve, reject) => reject('sendMessage require param[text].'));
}
var data = {'chat_id': config.chat_id, 'text': text,
'disable_web_page_preview': config.disable_web_page_preview,
'parse_mode': config.parse_mode};
sendToTelegram('sendMessage', data);
}
function sendPhoto(filename, image, reply_to) {
if (!filename) {
return;// new Promise((resolve, reject) => reject('sendPhoto require param[filename].'));
}
if (!(image instanceof Buffer) || !image.length) {
return;// new Promise((resolve, reject) => reject('sendPhoto require param[image] <Buffer>.'));
}
let data = {
chat_id : config.chat_id,
photo : image,// document : <Buffer>,
fullpath: filename,
parse_mode: config.parse_mode,
disable_notification: 'true',
caption : filename + ' #image'
};
if (parseInt(reply_to) > 0) {
data.reply_to_message_id = parseInt(reply_to);
}
sendToTelegram('sendPhoto', data);
}
function sendToTelegram(method, params) {
if (!method || (typeof params !== 'object') || (!config.bot_api_key)) {
return;// new Promise((resolve, reject) => reject(' sendToTelegram caught invalid params.'));
}
var url = config.telegram_api_endpoint_prefix + config.bot_api_key + '/' + method;
// callback, 'application/json'
if (config.debug_mode) {
let tmp = '';
Object.keys(params).forEach((k) => {
if (params[k] instanceof Buffer) {
tmp += k + ': <Buffer>,\n';
} else {
tmp += k + ': ' + params[k] +',\n';
}
});
console.log('sendToTelegram -> ' + tmp);
}
requestPost({'url': url, 'form': params});
if (config.debug_mode) {
console.log('sendToTelegram done.');
}
}
function requestPost(req, success = (text) => {return text}) {
let formData = req.form;
if (formData.hasOwnProperty('fullpath')) {
delete formData.fullpath;
}
console.log(formData);
var url = new String(req.url).toString();
request.post({'url': url, 'formData': formData}, (err, httpResponse, body) => {
if (err) {
return;// new Promise((resolve, reject) => reject('Error while XHR: ' + err));
}
console.log('XHR response: ', body, url);
return success(body);
});
}
/*
実行結果:bot_api_keyマスク済
naoto$ node node-request-test.js
Sun Jul 01 2018 15:34:43 GMT+0900 (JST) START /////////////////////////////////////////////////////////////
sendToTelegram -> chat_id: -1001119217627,
text: its you!,
disable_web_page_preview: true,
parse_mode: HTML,
{ chat_id: '-1001119217627',
text: 'its you!',
disable_web_page_preview: 'true',
parse_mode: 'HTML' }
sendToTelegram done.
20050828_tokyogeosite4_.jpg Buffer
sendToTelegram -> chat_id: -1001119217627,
photo: <Buffer>,
fullpath: 20050828_tokyogeosite4_.jpg,
parse_mode: HTML,
disable_notification: true,
caption: 20050828_tokyogeosite4_.jpg #image,
{ chat_id: '-1001119217627',
photo: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff db 00 43 00 0d 09 0a 0b 0a 08 0d 0b 0a 0b 0e 0e 0d 0f 13 20 15 13 12 12 13 27 1c 1e 17 ... >,
parse_mode: 'HTML',
disable_notification: 'true',
caption: '20050828_tokyogeosite4_.jpg #image' }
sendToTelegram done.
XHR response: {"ok":true,"result":{"message_id":3154,"from":{"id":356700597,"is_bot":true,"first_name":"\u30b7\u30e5\u30ac\u30fc\u30ab\u30c3\u30c8","username":"RnR_LogArchive_bot"},"chat":{"id":-1001119217627,"title":"isnot\u30c6\u30b9\u30c8","type":"supergroup"},"date":1530426884,"text":"its you!"}} https://api.telegram.org/bot356700597:AAAAAA/sendMessage
XHR response: {"ok":false,"error_code":400,"description":"Bad Request: wrong URL host"} https://api.telegram.org/bot356700597:AAAAAA/sendPhoto
*/
@isnot
Copy link
Author

isnot commented Jul 1, 2018

const telegram = require('telegram-bot-api');

let api = new telegram({token: config.bot_api_key});
api.sendPhoto({
chat_id: config.chat_id,
caption: 'This is my test image',
photo: path
}).then((data) => {
console.log(data);
});

これで解決した

@isnot
Copy link
Author

isnot commented Jul 2, 2018

↑と思ったら、やはりBufferから直接送信ができません。

実際の解決方法は
https://stackoverflow.com/questions/43913650/how-to-send-a-buffer-in-form-data-to-signserver

form.append('data', file_buffer, { filename : 'document.pdf' });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment