Giter VIP home page Giter VIP logo

telegram-bot-simple's People

Contributors

21it avatar alininium avatar anpryl avatar badochov avatar balsoft avatar daapp avatar deemp avatar drewfenwick avatar eisfunke avatar fetsh-edu avatar fizruk avatar gdanix avatar lispandfound avatar matobet avatar mic92 avatar p4vook avatar qnikst avatar s-and-witch avatar seteh avatar snu5mumr1k avatar srgtmshnk avatar swamp-agr avatar vyorkin avatar worm2fed avatar zlonast 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

telegram-bot-simple's Issues

Version 6.0 won't compile

Trying to compile the latest version from github.
Getting this errors:

telegram-bot-simple/src/Telegram/Bot/API/Types.hs:563:65: error:
    No instance for (ToJSON WebAppInfo) arising from a use of ‘.=’
    In the expression: "web_app_info" .= wai
     In the second argument of addType, namely
       ["text" .= txt, "web_app_info" .= wai]
     In the second argument of ($), namely
       addType "web_app" ["text" .= txt, "web_app_info" .= wai]
   |                              
563 |       object $ addType "web_app" ["text" .= txt, "web_app_info" .= wai]
   |                                                                 ^^
                                  
/telegram-bot-simple/src/Telegram/Bot/API/Types.hs:571:15: error:
    No instance for (FromJSON WebAppInfo)
       arising from a use of gparseJSON
    In the expression: gparseJSON
     In an equation for parseJSON’: parseJSON = gparseJSON
     In the instance declaration for FromJSON MenuButton
   |                              
571 |   parseJSON = gparseJSON

stack ghc -- --version
The Glorious Glasgow Haskell Compilation System, version 9.0.1

stack --version
Version 2.7.3, Git revision 7927a3aec32e2b2e5e4fb5be76d0d50eddcc197f x86_64 hpack-0.34.4

Build failure with GHC 9.0

$ cabal build -w ghc-9.0
src/Telegram/Bot/API/Types.hs:1027:30: error:
    • No instance for (ToJSON PassportElementError)
        arising from a use of ‘encodeToLazyText’
    • In the second argument of ‘(.)’, namely ‘encodeToLazyText’
      In the expression: TL.toStrict . encodeToLazyText
      In an equation for ‘toUrlPiece’:
          toUrlPiece = TL.toStrict . encodeToLazyText
     |
1027 |   toUrlPiece = TL.toStrict . encodeToLazyText
     |                              ^^^^^^^^^^^^^^^^

src/Telegram/Bot/API/Types.hs:1030:30: error:
    • No instance for (ToJSON PassportElementError)
        arising from a use of ‘encodeToLazyText’
    • In the second argument of ‘(.)’, namely ‘encodeToLazyText’
      In the expression: TL.toStrict . encodeToLazyText
      In an equation for ‘toUrlPiece’:
          toUrlPiece = TL.toStrict . encodeToLazyText
     |
1030 |   toUrlPiece = TL.toStrict . encodeToLazyText
     |                              ^^^^^^^^^^^^^^^^

src/Telegram/Bot/API/Types.hs:1146:50: error:
    • No instance for (ToJSON MessageEntity)
        arising from a use of ‘gtoJSON’
    • In the expression: gtoJSON
      In an equation for ‘toJSON’: toJSON = gtoJSON
      In the instance declaration for ‘ToJSON InputMediaGeneric’
     |
1146 | instance ToJSON InputMediaGeneric where toJSON = gtoJSON
     |                                                  ^^^^^^^

src/Telegram/Bot/API/Types.hs:1156:55: error:
    • No instance for (ToJSON MessageEntity)
        arising from a use of ‘encodeToLazyText’
    • In the second argument of ‘($)’, namely ‘encodeToLazyText t’
      In the second argument of ‘Input’, namely
        ‘(TL.toStrict $ encodeToLazyText t)’
      In the expression:
        Input "caption_entities" (TL.toStrict $ encodeToLazyText t)
     |
1156 |         \t -> Input "caption_entities" (TL.toStrict $ encodeToLazyText t)
     |                                                       ^^^^^^^^^^^^^^^^^^

Cf. #46.

Bot API 6.0

Bot API 6.0

• Added support for Web Apps.
KeyboardButton and InlineKeyboardButton can now be used to launch Web Apps.
• Added control over the bot's menu button via setChatMenuButton and getChatMenuButton.
• Added control over the bot's default admin rights via setMyDefaultAdministratorRights and getMyDefaultAdministratorRights.
• Added support for t.me links to add bots as admins.

• And more, see the full changelog for details:

https://core.telegram.org/bots/api-changelog#april-16-2022

Warning: After the next update, login_url will only allow HTTPS links.

Notification in send document can't be disabled

Even if we set sendDocumentDisableNotification = Just True, the message is still sent with notification.

How to reproduce:

  1. Send document without notifications:
      defaultRunBot (fromString token) $
        sendDocument
          (toSendDocument
             chat_id
              (DocumentFile archive_path "application/zip"))
                { sendDocumentCaption = Just "some caption.zip")
                , sendDocumentDisableNotification = Just True
                }

Expected results:

Message will be delivered without notification. There will be strikethrough bell icon near the message.

Actual results:

Message is delivered with notifications

stack build fails with No instance for (MonadFail UpdateParser)

No instance for (MonadFail UpdateParser)/home/vyorkin/projects/github/haskell/telegram-bot-simple/src/Telegram/Bot/Simple/UpdateParser.hs:43:10: error:
    • No instance for (MonadFail UpdateParser)
        arising from a use of ‘fail’
    • In the expression: fail "command"
      In a stmt of a 'do' block:
        if "/" `Text.isPrefixOf` t then fail "command" else pure t
      In the expression:
        do t <- text
           if "/" `Text.isPrefixOf` t then fail "command" else pure t
   |
43 |     then fail "command"
   |          ^^^^^^^^^^^^^^

Maybe this is because the instance was accidentally deleted cbe7f38#diff-578fc2ec77b209d8f0088375d3801054L30-L32

Payments: Bot API 5.5

GHC 9 Compilation failure

Building library for telegram-bot-simple-0.3.5..               
                                                                                                                                                                                           
src/Telegram/Bot/API/Types.hs:436:1: error:
    • No instance for (FromJSON ChatPhoto)
        arising from a use of ‘parseJSON’
    • In the first argument of ‘Data.Aeson.TH.lookupField’, namely
        ‘parseJSON’
      In the second argument of ‘(<*>)’, namely
        ‘((((Data.Aeson.TH.lookupField parseJSON)
              "Telegram.Bot.API.Types.Chat")
             "")
            recObj_akPn)
           (pack "photo")’
      In the first argument of ‘(<*>)’, namely
        ‘((((((((Chat
                   <$>
                     ((((Data.Aeson.TH.lookupField parseJSON)
                          "Telegram.Bot.API.Types.Chat")
                         "")
                        recObj_akPn)
                       (pack "id"))
                  <*>
                    ((((Data.Aeson.TH.lookupField parseJSON)
                         "Telegram.Bot.API.Types.Chat")
                        "")
                       recObj_akPn)
                      (pack "type"))
                 <*>
                   ((((Data.Aeson.TH.lookupField parseJSON)
                        "Telegram.Bot.API.Types.Chat")
                       "")
                      recObj_akPn)
                     (pack "title"))
                <*>
                  ((((Data.Aeson.TH.lookupField parseJSON)
                       "Telegram.Bot.API.Types.Chat")
                      "")
                     recObj_akPn)
                    (pack "username"))
               <*>
                 ((((Data.Aeson.TH.lookupField parseJSON)
                      "Telegram.Bot.API.Types.Chat")
                     "")
                    recObj_akPn)
                   (pack "first_name"))
              <*>
                ((((Data.Aeson.TH.lookupField parseJSON)
                     "Telegram.Bot.API.Types.Chat")
                    "")
                   recObj_akPn)
                  (pack "last_name"))
             <*>
               ((((Data.Aeson.TH.lookupField parseJSON)
                    "Telegram.Bot.API.Types.Chat")
                   "")
                  recObj_akPn)
                 (pack "all_members_are_administrators"))
            <*>
              ((((Data.Aeson.TH.lookupField parseJSON)
                   "Telegram.Bot.API.Types.Chat")
                  "")
                 recObj_akPn)
                (pack "photo"))’
    |
436 | deriveJSON' ''Chat
    | ^^^^^^^^^^^^^^^^^^

Error using botJob with cron < 0.7

Please, specify cron version as >= 0.7.0 in package.yaml as dependencies, because botJob is unusable otherwise - MichaelXavier/cron#41 . Previous version of cron try to parse incorrect time, for example "2020-11-12 13:60" with error and bot stop working.

High CPU usage

Even running TODO Bot from example takes up up to 10% of my CPU on idle when no messages are sent on any of the chat the bot is on. It's in my opinion unacceptable.

Inconsistency in parseMode fields

Some objects are using PareseMode type (SendMessageRequest, SendDocumentRequest, SendPhotoRequest, etc) for theirs parseMode field, and some others just Text (SendAudioRequest, SendVideoRequest, etc).

This PR #114 should fix it.

Oudated Types: Bot API 5.5

  • User:
    • + can_join_groups, can_read_all_group_messages, supports_inline_queries.
  • Chat:
    • - all_members_are_administrators.
    • + bio, permissions, slow_mode_delay, message_auto_delete_time, has_protected_content, linked_chat_id, location.
  • Message:
    • + sender_chat, forward_sender_name, is_automatic_forward, via_bot, has_protected_content, animation, caption_entities, dice, poll, game, message_auto_delete_timer_changed, invoice, successful_payment, connected_website, passport_data, proximity_alert_triggered, voice_chat_scheduled, voice_chat_started, voice_chat_ended, voice_chat_participants_invited, reply_markup .
  • MessageEntity:
    • + language.
  • PhotoSize:
    • + file_unique_id.
  • Audio:
    • + file_unique_id, filename, thumb.
  • Document:
    • + file_unique_id.
  • Video:
    • + file_unique_id, file_name.
  • VideoNote:
    • + file_unique_id.
  • Voice:
    • + file_unique_id.
  • Contact:
    • + vcard.
  • ReplyKeyboardMarkup :
    • + input_field_placeholder .
  • Sticker:
    • + mask_position.
  • KeyboardButton:
    • + request_poll.
  • InlineKeyboardButton:
    • + login_url, callback_game.
  • ChatPhoto:
    • + small_file_unique_id, big_file_unique_id.

Error while parsing Int32

I use version 0.3.4.
I've got this in my bot:
DecodeFailure "Error in $.result[0].message.from.id: parsing Int32 failed, value is eithe
r floating or will cause over or underflow 5.067420826e9" (Response {responseStatusCode = Status {statusCode = 200, statusMessage = "OK"}, response
Headers = fromList [("Server","nginx/1.18.0"),("Date","Mon, 20 Dec 2021 13:21:11 GMT"),("Content-Type","application/json"),("Content-Length","399")
,("Connection","keep-alive"),("Strict-Transport-Security","max-age=31536000; includeSubDomains; preload"),("Access-Control-Allow-Origin","*"),("Acc
ess-Control-Allow-Methods","GET, POST, OPTIONS"),("Access-Control-Expose-Headers","Content-Length,Content-Type,Date,Server,Connection")], responseH
ttpVersion = HTTP/1.1, responseBody = "{"ok":true,"result":[{"update_id":68483329,\n"message":{"message_id":27943,"from":{"id":5067420826,

Looks like last number in fragment parsed incorrectly.

From telegram bot api:
Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.

I have read changes up to 0.3.8 and find no fix for this.

Error `Couldn't match type ‘ClientEnv’ with ‘Maybe a0 -> ClientEnv’`

I get the following error when building as a dependency for my project:

[ 6 of 13] Compiling Telegram.Bot.API.MakingRequests ( src/Telegram/Bot/API/MakingRequests.hs, .stack-work/dist/x86_64-linux-nopie/Cabal-1.24.2.0/build/Telegram/Bot/API/MakingRequests.o )
    
    /home/legopelle/owncloud/programming/haskell/telegram-bot-simple/src/Telegram/Bot/API/MakingRequests.hs:24:34: error:
        • Couldn't match type ‘ClientEnv’ with ‘Maybe a0 -> ClientEnv’
          Expected type: IO (Maybe a0 -> ClientEnv)
            Actual type: IO ClientEnv
        • In the first argument of ‘(<*>)’, namely
            ‘ClientEnv <$> newManager tlsManagerSettings
             <*> pure (botBaseUrl token)’
          In the expression:
            ClientEnv <$> newManager tlsManagerSettings
            <*> pure (botBaseUrl token)
            <*> pure Nothing
          In an equation for ‘defaultTelegramClientEnv’:
              defaultTelegramClientEnv token
                = ClientEnv <$> newManager tlsManagerSettings
                  <*> pure (botBaseUrl token)
                  <*> pure Nothing

Any ideas why?

DecodeFailure on copyMessage

copyMessage expects MessageId as a result, but receives an object {"message_id": x},
so it fails with DecodeFailure "Error in $.result: parsing Integer failed, expected Number, but encountered Object"

This PR #116 should fix it.

Missing Methods: Bot API 5.5

Missing Types: Bot API 5.5

Telegram Passport: Bot API 5.5

Upload haddock to hackage

See here for how to upload the haddock, plus some troubleshooting steps if it doesn't work automatically.

I believe all you need to do is stack haddock && stack upload.

Note for anyone else looking for the docs: you can build the docs locally, just do stack haddock and it will put the docs in somewhere like /.stack-work/install/x86_64-linux-nix/lts-11.15/8.2.2/doc/telegram-bot-simple-0.2.0/index.html

Bot API 6.6

Bot API 6.6

See https://core.telegram.org/bots/api for changelog

  1. new setMyDescription method
  2. new getMyDescription method
  3. new setMyShortDescription method
  4. new getMyShortDescription method
  5. modify sendSticker: add emoji
  6. modify createNewStickerSet:
    • modify sticker -> stickers (see below),
    • new InputSticker type (some fields from request should move here),
    • new sticker_format field,
    • new sticker_type field
    • new needs_repainting field.
  7. modify Sticker type add needs_repainting field.
  8. modify addStickerToSet method:
    • modify sticker -> stickers (see below),
    • use InputSticker type (again some fields from request should move here).
  9. modify uploadStickerFile method (request):
    • remove png_sticker field,
    • add sticker field,
    • add sticker_format field.
  10. new setCustomEmojiStickerSetThumbnail method.
  11. new setStickerSetTitle method.
  12. new deleteStickerSet method.
  13. new setStickerEmojiList method.
  14. new setStickerKeywords method.
  15. new setStickerMaskPosition method.
  16. rename the field thumb in the classes Animation, Audio, Document, Sticker, Video, VideoNote, InputMediaAnimation, InputMediaAudio, InputMediaDocument, InputMediaVideo, StickerSet to thumbnail.
  17. rename the parameter thumb in the methods sendAnimation, sendAudio, sendDocument, sendVideo, sendVideoNote to thumbnail.
  18. rename the method setStickerSetThumb to setStickerSetThumbnail and its parameter thumb to thumbnail.
  19. rename the fields thumb_url, thumb_width, and thumb_height in the classes InlineQueryResultArticle, InlineQueryResultContact, InlineQueryResultDocument, InlineQueryResultLocation, and InlineQueryResultVenue to thumbnail_url, thumbnail_width, and thumbnail_height respectively.
  20. rename the field thumb_url in the classes InlineQueryResultPhoto and InlineQueryResultVideo to thumbnail_url.
  21. rename the fields thumb_url and thumb_mime_type in the classes InlineQueryResultGif, and InlineQueryResultMpeg4Gif to thumbnail_url and thumbnail_mime_type respectively.

Given the amount of new stickers method it is reasonable to split the module onto multiple sub-modules and then re-import them in Telegram.Bot.API.Stickers.

`Telegram.Bot.API.UpdatingMessages.editMessageReplyMarkup` is seemingly broken

When trying to use editMessageReplyMarkup, I get the following error:

Left (DecodeFailure "Error in $.result: expected an object with a single property where the property key should be either \"Left\" or \"Right\"" (Response {responseStatusCode = Status {statusCode = 200, statusMessage = "OK"}, responseHeaders = fromList [("Server","nginx/1.18.0"),("Date","Thu, 22 Dec 2022 19:59:59 GMT"),("Content-Type","application/json"),("Content-Length","779"),("Connection","keep-alive"),("Strict-Transport-Security","max-age=31536000; includeSubDomains; preload"),("Access-Control-Allow-Origin","*"),("Access-Control-Allow-Methods","GET, POST, OPTIONS"),("Access-Control-Expose-Headers","Content-Length,Content-Type,Date,Server,Connection")], responseHttpVersion = HTTP/1.1, responseBody = "{\"ok\":true,\"result\":{\"message_id\":<snip>}}"}))

(The gist is that aeson tries to parse result as a sum type data Either a b = Left a | Right b, which the value does not satisfy)

I haven't tested other edit* functions.

I'm using telegram-bot-simple-0.4.5, and aeson-2.0.3.0

Why BotM has to end with an action?

It looks like ending BotM with pure NoAction is boilerplate. As well as handleAction NoAction = pure model.

So, an extra action is always issued.

And user Action is always ~ Maybe Action'.

At the same time, botAction allows for the absence of action with Maybe in its signature.

Is Eff really needed? How to send a message without an extra action?

Problems with demo-bot.exe

So i finally solved all the problems with libraries, but when I'm trying to run exe file to put in Telegram.Token, it's just don't want to work

Stickers: Bot API 5.5

Errors from the actions are consumed without any messages

Currently all the errors from the telegram server (ones that runClietM is returned with) are consumed without any trace. It's very inconvenient to debug the bot in this setting. For the local debugging I've added:

 processActionsIndefinitely botApp botEnv = forkIO . forever $ do
-  runClientM (processActionJob botApp botEnv) (botClientEnv botEnv)
+  runClientM (processActionJob botApp botEnv) (botClientEnv botEnv) >>= \case
+     Right x -> pure ()
+     Left e -> print e

That at least logs the results so it's possible to see what has gone wrong. But ideally there should be some better solution, like installing own exception handler. Also it would be nice to be able to catch such exceptions from the actions, for example if bot resends a message that could fail due to the bad markup and we want to send an totally escaped message in case of a error, or implement clever retry.

I can contribute an implementation if we agree on the design.

What is callbackQueryDataRead?

This function has type callbackQueryDataRead :: Read a => UpdateParser a ,is not documented, and used in todolist example, please add docs or comments

Delays in update handlers

Hi, I need to delay for a few seconds before replying to some certain messages, but do not need these replies to be ordered, that is, these replies should be "streamlined".

Q1 (delay for 1 sec)
Q2 (immediately follows Q1)
A1 (received after 1sec)
A2 (immediately follows A1)

I observed that the updates are received 'concurrently', but the actions are not: A2 appears after 2 secs.

It seems there is no easy support for this scenario currently, and I may need to use bot jobs. I looked into Internal.hs and it seems the actions are serialized by botActionsQueue. (If I understand it correctly.)

Is there a better way to do it with the current version of the library?

Implement document upload

For that we need to implement multipart/form-data support.
There is no general support for that in servant, so I think we should wait for fizruk/http-api-data#24.

Until then we can just copy over some code from somewhere.

Wrong type in EditMessageTextRequest record

The EditMessageTextRequest type contains a field editMessageTextRequestInlineMessageId which has type MessageId and is represented as Int.
Official Telegram Bot API documentation describes this parameter as a String.

It would be the right choice to make the inlineMessageId field of EditMessageRequest represented by Text instead of an Int

Screenshot from 2021-09-01 00-24-09
Screenshot from 2021-09-01 00-28-04

Conversation bot improvements

currentChatId always returns Maybe ChatId but in conversationBot we always have ChatId. It leads to meaningless boilerplate code every time ChatId is needed in handlers.
What do you think about ConversationM?
Here is example:

newtype ConversationM a =
  ConversationM { _runConversationM :: ReaderT (ChatId, Update) ClientM a }

@fizruk
Is there are any hidden issues which will block this improvement?
If you are OK with this I will try to create prototype next week.

Build failure with servant 0.16

[ 8 of 21] Compiling Telegram.Bot.API.MakingRequests ( src/Telegram/Bot/API/MakingRequests.hs, dist/build/Telegram/Bot/API/MakingRequests.o )

src/Telegram/Bot/API/MakingRequests.hs:31:51: error:
    Not in scope: type constructor or class ‘ServantError’
   |
31 | defaultRunBot :: Token -> ClientM a -> IO (Either ServantError a)
   |           

Bot name is very incovinient to access from UpdateParser

I found today it's really hard to parse commands in UpdateParser, becaus I need to parse the @my_bot_name part, but I don't have access to the name.

As far as I understand, I can get bot's User from BotM via reader botContextUser, or from BotEnv which is internal.

I can't use BotM's reader because that is created after botAction is created.

I can sort of use BotEnv, but it comes with two big downsides: I need to replicate startBot_ myself, and I need to use recursive do because, again, botAction must be created before I run startBotEnv

`command` UpdateParser is eating newlines

Currently command UpdateParser looks like lthis:

command :: Text -> UpdateParser Text
command name = do
  t <- text
  case Text.words t of
    (w:ws) | w == "/" <> name
      -> pure (Text.unwords ws)
    _ -> fail "not that command"

And because of words -> unwords all newlines of the message text vanish.

If this is an intended behavior, then ok.

For myself I'm using my version of command:

command :: Text -> UpdateParser Text
command name = do
    t <- text
    let (cmd, rest) = Text.break isSpace t
    if cmd == "/" <> name
        then pure $ stripStart rest
        else fail "not that command"

I can make a PR with this version, if loosing newlines was not intended and my version is fine codewise.

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.