reo7sp / tgbot-cpp Goto Github PK
View Code? Open in Web Editor NEWC++ library for Telegram bot API
Home Page: http://reo7sp.github.io/tgbot-cpp
License: MIT License
C++ library for Telegram bot API
Home Page: http://reo7sp.github.io/tgbot-cpp
License: MIT License
When I use the sample "inline-keyboard" on Android, the tapped button gets a spinning circle (as though waiting for answer). All everything else is ok.
Here the code:
#include <exception>
#include <tgbot/tgbot.h>
using namespace std;
using namespace TgBot;
int main() {
Bot bot(token);
InlineKeyboardMarkup::Ptr keyboard(new InlineKeyboardMarkup);
vector<InlineKeyboardButton::Ptr> row0;
InlineKeyboardButton::Ptr checkButton(new InlineKeyboardButton);
checkButton->text = "check";
checkButton->callbackData = "check";
row0.push_back(checkButton);
keyboard->inlineKeyboard.push_back(row0);
bot.getEvents().onCommand("start", [&bot, &keyboard](Message::Ptr message) {
bot.getApi().sendMessage(message->chat->id, "ok", false, 0, keyboard);
});
bot.getEvents().onCallbackQuery([&bot, &keyboard](CallbackQuery::Ptr query) {
if (StringTools::startsWith(query->data, "check")) {
bot.getApi().sendMessage(query->message->chat->id, "ok", false, 0, keyboard);
}
});
try {
printf("Bot username: %s\n", bot.getApi().getMe()->username.c_str());
TgLongPoll longPoll(bot);
while (true) {
longPoll.start();
}
} catch (TgException& e) {
printf("error: %s\n", e.what());
}
return 0;
}
In some methods reference to shared_ptr was passed to for example:
Message::Ptr sendPhoto(int64_t chatId, const InputFile::Ptr& photo
Message::Ptr sendAudio(int64_t chatId, const InputFile::Ptr& audio
I think its't corect.
If I create a thread for sending and pass InputFile::Ptr to send thread and detach thread, IntpuFile::Ptr reference counter == 0 and InputFile object will be destructions and send thread work with non valid memory.
I create pull request 605af0c
I found several errors related to the program during the compilation.
I would like to know if maybe it is also my fault, I'm new to programming in C++ !
I'm using Ubuntu 14.04 LTS and Codelite 8.0.
Log: http://pastebin.com/6LDFZDSG
This project is really very interesting!
Please, remove "iostream" from find_package() functions cause it's not needed. If ENABLE_TESTS=NO
Hi,
I success to compiled tgbot i ubuntu. But after try same methods in raspberry pi 3 model B i got this error:
//usr/local/lib/libTgBot.a(Url.cpp.o): In function `TgBot::Url::Url(std::string const&)':
Url.cpp:(.text+0x2f8): undefined reference to `StringTools::urlEncode(std::string const&, std::string)'
Url.cpp:(.text+0x378): undefined reference to `StringTools::urlEncode(std::string const&, std::string)'
Url.cpp:(.text+0x3f8): undefined reference to `StringTools::urlEncode(std::string const&, std::string)'
Url.cpp:(.text+0x478): undefined reference to `StringTools::urlEncode(std::string const&, std::string)'
//usr/local/lib/libTgBot.a(HttpParser.cpp.o): In function `TgBot::HttpParser::generateWwwFormUrlencoded(std::vector<TgBot::HttpReqArg, std::allocator<TgBot::HttpReqArg> > const&)':
HttpParser.cpp:(.text+0x844): undefined reference to `StringTools::urlEncode(std::string const&, std::string)'
//usr/local/lib/libTgBot.a(HttpParser.cpp.o):HttpParser.cpp:(.text+0x8c8): more undefined references to `StringTools::urlEncode(std::string const&, std::string)' follow
collect2: error: ld returned 1 exit status
Any suggestion?
Are there any plans to provide easy build support for windows?
Also packaging for vcpkg and nuget would be really cool.
I develop most of my applications on windows using visual studio and run them on a linux.
I have created a visual studio project in my fork but I consider it far from perfect because it is not automatically in sync with the source, you have to add new files manually.
It would be much better to generate the vs project using cmake or something like this.
{"ok":false,"error_code":400,"description":"Bad Request: group chat was migrated to a supergroup chat","parameters":{"migrate_to_chat_id":(chat id, int64_t)}};
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injectorboost::property_tree::json_parser::json_parser_error >'
what(): (1): expected value
Even when file was specified.
This error is not generated every time an image is sent.
everytime im trying to compile and after start i getting this
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injectorboost::system::system_error >'
what(): handshake: wrong version number
To fix the error add #include <vector>
to include/tgbot/net/HttpParser.h
Is the reception of voice notes supported?
mesage->voice
seems to be always null.
Thanks.
Hi, I had to remove two lines from tgbot.h to compile my application.
diff --git a/include/tgbot/tgbot.h b/include/tgbot/tgbot.h
index d393fc7..f377d1e 100644
--- a/include/tgbot/tgbot.h
+++ b/include/tgbot/tgbot.h
@@ -33,9 +33,7 @@
#include "tgbot/types/Contact.h"
#include "tgbot/types/Document.h"
#include "tgbot/types/ForceReply.h"
-#include "tgbot/types/GenericChat.h"
#include "tgbot/types/GenericReply.h"
-#include "tgbot/types/GroupChat.h"
#include "tgbot/types/InputFile.h"
#include "tgbot/types/Location.h"
#include "tgbot/types/Message.h"
I'm running a telegram bot with this library on my raspberry pi at home. When my internet connection gets lost (e.g. dsl reconnect, un-plug the pi and plug it in again) the connection to the telegram server is lost.
The LongPoll or HttpClient::makeRequest function does not run into a timeout, keeping the connection open waiting for a response never to arrive.
I implemented a timeout but my solution is not cross-platform. Maybe someone could implement a proper timeout using boost-functions?
My bot catches exception during longPoll.start()
call saying Forbidden: user blocked
(or something like this). I need to know which user has blocked my bot to disable my service subscription fir him/her. Thanks
If i send bot message like "привет", telegram return json like this
{
"ok":true,
"result":
[{
"update_id":97062,
"message":
{
"message_id":61,
"from":
{
"id":96202,
"first_name":"Aleksei",
"last_name":"Aleshin",
"username":"krepver"
},
"chat":
{
"id":96202,
"first_name":"Aleksei",
"last_name":"Aleshin",
"username":"krepver",
"type":"private"
},
"date":1460646730,
"text":"\u041f\u0440\u0438\u0432\u0435\u0442"
}
}]
}
error: undefined reference to `TgBot::Api::Api(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)'
I have been linking libraries as per given on github.
The Samples work just fine, when i try to implement in other programs, the program gives error.
Plus the library has a lot of issues with boost and gateway time outs.
I see that there is not a TIMEOUT implemented in libcurl. I think this can generate problems if the connection is lost. I'm right? It would be as follows:
/* For example, complete within 20 seconds */
curl_easy_setopt(curl, CURLOPT_TIMEOUT,20L);
In the next line to this:
tgbot-cpp/src/net/CurlHttpClient.cpp
Line 75 in 5a1bcfd
I am using the InlineReplyKeyboard and Google Protobuf to store the callback data. My code looks like this:
InlineKeyboardMarkup::Ptr keyboard(new InlineKeyboardMarkup);
std::vector<InlineKeyboardButton::Ptr> keyButtons;
InlineKeyboardButton::Ptr btnYes(new InlineKeyboardButton);
btnYes->text = "Yes";
it->second.set_flash(true);
btnYes->callbackData = it->second.SerializeAsString(); //here I call the SerializeAsString from the protobuf message
keyButtons.push_back(btnYes);
InlineKeyboardButton::Ptr btnNo(new InlineKeyboardButton);
btnNo->text = "No";
it->second.set_flash(false);
btnNo->callbackData = it->second.SerializeAsString(); //here I call the SerializeAsString from the protobuf message
keyButtons.push_back(btnNo);
keyboard->inlineKeyboard.push_back(keyButtons);
master->bot->getApi().sendMessage(message->chat->id, "Force flash?", false, 0, keyboard);
A string I want to send looks like this: �����" FF Karlshorst43774906
or as hex representation 080210011803220D4646204B61726C73686F72737432083433373734393036
. These are two strings, one containing a text and the other one the chat id as text.
The corresponding JSON generated by the TgTypeParser is:
{"inline_keyboard":[[{"text":"Yes","callback_data":�����"
FF Karlshorst43774906P�"},{"text":"No","callback_data":�����"
FF Karlshorst43774906"}]]}
or again as hex:
7B22696E6C696E655F6B6579626F617264223A5B5B7B2274657874223A22596573222C2263616C6C6261636B5F64617461223A22080210011803220D4646204B61726C73686F727374320834333737343930365001227D2C7B2274657874223A224E6F222C2263616C6C6261636B5F64617461223A22080210011803220D4646204B61726C73686F72737432083433373734393036227D5D5D7D
Whit this I get the error message: Bad Request: can't parse reply keyboard markup JSON object
. I already tried to put quotation marks manually around the serialized object but had no luck.
I would like to add that I used similar code and got no errors. I have no idea why now... Help is much appreciated.
Good day,
I am a Windows user and want to use this library. Thus, I downloaded the repository, and followed the instructions of this video as I am quite a beginner in programming: https://www.youtube.com/watch?v=LxHV-KNEG3k&t
I get following errors:
CMake Error at D:/Programme/CMake/share/cmake-3.13/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
Call Stack (most recent call first):
D:/Programme/CMake/share/cmake-3.13/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
D:/Programme/CMake/share/cmake-3.13/Modules/FindZLIB.cmake:114 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
CMakeLists.txt:44 (find_package)
Configuring incomplete, errors occurred!
See also "D:/Downloads/CMakeFiles/CMakeOutput.log".
See also "D:/Downloads/CMakeFiles/CMakeError.log".
Could you help me please?
Hi @reo7sp
try to compile this file in Ubuntu - codeblocks by this command:
g++ main.cpp -o main -std=c++11
but I have this errors:
/tmp/ccHNsyWI.o: In function
main::{lambda(std::shared_ptr<TgBot::Message>)#2}::operator()(std::shared_ptr<TgBot::Message>) const': main.cpp:(.text+0x1b0): undefined reference to
TgBot::Api::sendMessage(int, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, bool, int, std::shared_ptrTgBot::GenericReply const&) const'
/tmp/ccHNsyWI.o: In functionmain::{lambda(std::shared_ptr<TgBot::Message>)#3}::operator()(std::shared_ptr<TgBot::Message>) const': main.cpp:(.text+0x2d9): undefined reference to
StringTools::startsWith(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)'
main.cpp:(.text+0x38c): undefined reference toTgBot::Api::sendMessage(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, int, std::shared_ptr<TgBot::GenericReply> const&) const' /tmp/ccHNsyWI.o: In function
main':
main.cpp:(.text+0x601): undefined reference toTgBot::Api::getMe() const' main.cpp:(.text+0x65e): undefined reference to
TgBot::TgLongPoll::TgLongPoll(TgBot::Bot const&)'
main.cpp:(.text+0x68b): undefined reference toTgBot::TgLongPoll::start()' /tmp/ccHNsyWI.o: In function
__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0xecb): undefined reference toboost::system::generic_category()' main.cpp:(.text+0xed5): undefined reference to
boost::system::generic_category()'
main.cpp:(.text+0xedf): undefined reference toboost::system::system_category()' /tmp/ccHNsyWI.o: In function
TgBot::Bot::Bot(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&)':
main.cpp:(.text._ZN5TgBot3BotC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE[_ZN5TgBot3BotC5ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE]+0x27): undefined reference toTgBot::Api::Api(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' /tmp/ccHNsyWI.o: In function
boost::asio::error::get_system_category()':
main.cpp:(.text._ZN5boost4asio5error19get_system_categoryEv[_ZN5boost4asio5error19get_system_categoryEv]+0x7): undefined reference to `boost::system::system_category()'
collect2: error: ld returned 1 exit status
please help me solve this problem
Hi! I'm not really familiar with boost nor with Linux development, so I'm kinda stuck here.
I'm using the sample code in the README file, but here's what happens when I execute it:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::ptree_bad_path> >' what(): No such node (first_name) Aborted (core dumped)
I'm not sure what is happening here. I managed to run it perfectly fine for a few times, then it started happening. I think it was after a friend forwarded 3 messages in a group chat, but I'm not sure. Since then, it stopped working.
The code is the same as in here, but with my proper token. Any help is appreciated.
Thanks!
Is it possible. I can see that in examples what currently bot can only 'answer' on user queries. But what if I want have some updates by time on my bot code?
Is this possible edit already send message? For example I adding '..' to '...' in message for showing 'progress' to user?
Afterdowngrading to 1e-51 it works again. I'd like a more permanent solution.
Refer to Bot API changelog: https://core.telegram.org/bots/api-changelog
Payment Platform
See Introduction to Bot Payments for a brief overview. If you're not a developer, you may like this user-friendly blog post better.
Video Messages
Multilingual Bots
More power to admin bots
Minor Changes
I'm init my bot as:
CurlHttpClient curlHttpClient;
Bot bot(token, curlHttpClient);
But when i'm trying to use sendPhoto
with InputFile::Ptr
arg i'm always received error: Bad Request: wrong URL host
, bcz CurlHttpClient implementation seems doesn't handle InputFile in makeRequest
. If we have photo
in std::vector<HttpReqArg>& args
seems it tries to send it's content as param, not as a file (mean, in POST we have photo=<content_of_file>
).
@egorpugin ^^
hi, during compilation it says:
\include\tgbot\net\TgWebhookLocalServer.h:40: error: 'local' is not a member of 'boost::asio'
what is the workaround ?
Missing optional fields returned by Telegram are not handled safely, for example by consistently using data.get() with a default value.
Test case:
Having the bot inside a group,
messages do not come with a first_name field.
Results in exception because ptree::get throws if it can't find the field in calls like
result->firstName = data.get("first_name");
Solution that worked for me:
result->firstName = data.get("first_name" , "" );
CMakeLists.txt: Please, use -W3 to show only important warning.
If internet connection fail, bot will stop in (write(socket, buffer(requestText.c_str(), requestText.length())); (or read, I did't check yet)).
Deadline timer can be used in this case (example http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp ).
@reo7sp, maybe it´s time to do it?
Please, add define variable to choose type of library. Thanks!
GenericReply::Ptr TgTypeParser::parseJsonAndGetGenericReply(const boost::property_tree::ptree& data) const function isn't used anywhere. Also it has control reaches end of non-void function.
TgTypeParser.cpp has grown to big. We can refactor its method into each types.
Hi,
Probably using curl for web requests could be more profit.
E.g. it could use proxies to overcome any telegram blocking issues.
I'd like to try to prepare a PR with such changes.
Is they welcome?
I have an echobot which is running on an ARM Board. The bot application simply gets updates and reply's back to the messages or commands that are received at the bot.
The bot is continuously running without any crashes or interruptions. When i try to send any command, the bot does not reply back anything.
I am not sure what is the correct term, but is there any timeout of the bot, which can be disabled so that the bot can run indefinitely ? Since it is an ARM board, and running headless, there is no chance to figure out what exactly is going on.
Some more Details :
Any possible solution that i need to implement inorder to make sure that the bot is getting the updates ?
tgbot/include/tgbot/net/TgWebhookServer.h:40:35: error: lambda capture 'this' is not used [-Werror,-Wunused-lambda-capture]
HttpServer(acceptor, [this, eventHandler, &path](const std::string& data, const std::map<std::string, std::string>& headers) -> std::string {
TgBot::Message::Ptr message->voice
Equals nullptr even if voice sent.
Hello. I have a Linux Mint 17.3. I did everything as it's written at docs. When I compiled sample programm, it gave me lots of error (in file). What should I do? Thanks
tlg_error.txt
Can you please give an example for sendPhoto method?
I couldnt get it to work
In net/HttpParser.cpp
such a code can be found:
string HttpParser::generateRequest(const Url& url, const vector<HttpReqArg>& args, bool isKeepAlive) {
string result;
if (args.empty()) {
result += "GET ";
} else {
result += "POST ";
}
result += url.path;
result += url.query.empty() ? "" : "?" + url.query;
result += " HTTP/1.1\r\n";
result += "Host: ";
result += url.host;
result += "\r\nConnection: ";
if (isKeepAlive) {
result += "keep-alive";
} else {
result += "close";
}
result += "\r\n";
if (args.empty()) {
result += "\r\n";
} else {
string requestData;
string bondary = generateMultipartBoundary(args);
if (bondary.empty()) {
result += "Content-Type: application/x-www-form-urlencoded\r\n";
requestData = generateWwwFormUrlencoded(args);
} else {
result += "Content-Type: multipart/form-data; boundary=";
result += bondary;
result += "\r\n";
requestData = generateMultipartFormData(args, bondary);
}
result += "Content-Length: ";
result += lexical_cast<string>(requestData.length());
result += "\r\n\r\n";
result += requestData;
}
return result;
}
It's not the best practice to concatenate strings cause it can spend more time than std::stringstream
from <sstream>
header with operator<<
.
In line 83 in include/tgbot/net/HttpServer.h
, it should be HttpParser::getInstance().parseResponse
instead of HttpParser::parseResponse
.
https://github.com/reo7sp/tgbot-cpp/blob/master/include/tgbot/net/HttpServer.h#L83
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.