Giter VIP home page Giter VIP logo

tgbot-cpp's People

Contributors

aadeg avatar andijcr avatar asapelkin avatar behrouz-m avatar dan4ik605743 avatar dmikushin avatar egorpugin avatar flode avatar gravechapa avatar ingjieye avatar jellybrick avatar kukin-konstantin avatar llnulldisk avatar mpsspm avatar naveenvhegde avatar nesc1 avatar nitanmarcel avatar ogretransporter avatar pan93412 avatar paulusel avatar r4d1sh avatar reo7sp avatar royna2544 avatar temomik avatar wtdcode avatar xdqi avatar xvitaly avatar yjbeetle avatar ymuv avatar zamazan4ik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tgbot-cpp's Issues

Api: callback button spinning circle

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.
image

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;
}

Reference to shared_ptr

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

Compilation error

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!

Remove boost iostream

Please, remove "iostream" from find_package() functions cause it's not needed. If ENABLE_TESTS=NO

Error compiling on Raspberry Pi 3

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?

Windows Build (msvc, vcpkg, nuget)

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.

TgTypeParser: parse error

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.

BoostHttpOnlySslClient: ssl error

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

Receiving voice notes

Is the reception of voice notes supported?
mesage->voice seems to be always null.

Thanks.

Build fails

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"

BoostHttpOnlySslClient: no timeouts

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?

TgTypeParser: handle user blocked case

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

Error handling Unicode messages

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"
  }
 }]
}

But message->text field is "\177\177\177\177\177\177"
wr_message

Api: link error

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.

Curl timeout is not implemented

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:

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteString);

TgTypeParser: wrong json serialization in InlineKeyboardMarkup

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.

Error when trying to build with CMake in Windows

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?

undefined reference to `TgBot::Api::sendMessage` in Ubuntu - codebloks

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 toTgBot::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 function main::{lambda(std::shared_ptr<TgBot::Message>)#3}::operator()(std::shared_ptr<TgBot::Message>) const': main.cpp:(.text+0x2d9): undefined reference toStringTools::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 to TgBot::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 functionmain':
main.cpp:(.text+0x601): undefined reference to TgBot::Api::getMe() const' main.cpp:(.text+0x65e): undefined reference toTgBot::TgLongPoll::TgLongPoll(TgBot::Bot const&)'
main.cpp:(.text+0x68b): undefined reference to TgBot::TgLongPoll::start()' /tmp/ccHNsyWI.o: In function__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0xecb): undefined reference to boost::system::generic_category()' main.cpp:(.text+0xed5): undefined reference toboost::system::generic_category()'
main.cpp:(.text+0xedf): undefined reference to boost::system::system_category()' /tmp/ccHNsyWI.o: In functionTgBot::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 to TgBot::Api::Api(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' /tmp/ccHNsyWI.o: In functionboost::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

Sample echo bot not working.

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!

Edit bot message

Is this possible edit already send message? For example I adding '..' to '...' in message for showing 'progress' to user?

Bot API 3.0 support.

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.

  • Added new kinds of updates, shipping_query and pre_checkout_query, and new types of message content, invoice and successful_payment.
  • Added new methods for payments: sendInvoice, answerShippingQuery, and answerPreCheckoutQuery.
  • Added a new type of button, the pay button to InlineKeyboardButton.

Video Messages

  • Added the sendVideoNote method, the new field video_note to Message, the fields record_video_note or upload_video_note to sendChatAction.

Multilingual Bots

  • The User object now may have a language_code field that contains the IETF language tag of the user's language.

More power to admin bots

  • New method deleteMessage that allows the bot to delete its own messages, as well as messages posted by other in groups and channels where the bot is an administrator.

Minor Changes

  • Replaced the field new_chat_member in Message with new_chat_members (the old field will still be available for a while for compatibility purposes).
  • New fields gif_duration in InlineQueryResultGif and mpeg4_duration in InlineQueryResultMpeg4Gif.

CurlHttpClient: sendPhoto method issue

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 ^^

Unsafe extraction of optional fields (exception when getting messages from groups : property first_name is not present)

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" , "" );

Use curl instead of own HttpClient

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?

Unresponsive bot - Bot does not reply back

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 :

  1. A script which invokes the application is in rc.local
  2. The Bot runs for first few hours, and then after couple of hours of dormancy, the bot is unresponsive. The bot does not freezes, but i guess does not get any updates.

Any possible solution that i need to implement inorder to make sure that the bot is getting the updates ?

During the compilation with -Werror an error occures

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 {

photo upload

Can you please give an example for sendPhoto method?
I couldnt get it to work

`HttpParser` uses `std::string` concatenation to build http request body. Would be better to use `std::stringstream`

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<<.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.