Class: Telepost
- Inherits:
-
Object
- Object
- Telepost
- Defined in:
- lib/telepost.rb
Overview
Telepost is a simple gateway to Telegram, which can post messages and respond to primitive requests:
require 'telepost'
tp = Telepost.new('... secret token ...')
tp.run do |chat, msg|
# Reply to the message via tp.post(msg, chat)
end
For more information read README file.
- Author
-
Yegor Bugayenko (yegor256@gmail.com)
- Copyright
-
Copyright © 2018-2024 Yegor Bugayenko
- License
-
MIT
Defined Under Namespace
Instance Attribute Summary collapse
-
#client ⇒ Object
readonly
To make it possible to get the client.
Instance Method Summary collapse
-
#initialize(token, chats: []) ⇒ Telepost
constructor
Makes a new object.
-
#post(chat, *lines) ⇒ Object
Post a single message to the designated chat room.
-
#run ⇒ Object
You can run a chat bot to listen to the messages coming to it, in a separate thread.
-
#spam(*lines) ⇒ Object
Send the message (lines will be concatenated with a space between them) to the chats provided in the constructor and encapsulated.
Constructor Details
#initialize(token, chats: []) ⇒ Telepost
Makes a new object. To obtain a token you should talk to the @BotFather in Telegram.
72 73 74 75 76 |
# File 'lib/telepost.rb', line 72 def initialize(token, chats: []) @token = token @client = Telebot::Client.new(token) @chats = chats end |
Instance Attribute Details
#client ⇒ Object (readonly)
To make it possible to get the client.
68 69 70 |
# File 'lib/telepost.rb', line 68 def client @client end |
Instance Method Details
#post(chat, *lines) ⇒ Object
Post a single message to the designated chat room. The chat argument can either me an integer, if you know the chat ID, or the name of the channel (your bot has to be the admin there). The lines provided will be concatenated with a space between them.
112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/telepost.rb', line 112 def post(chat, *lines) msg = lines.join(' ') @client.( chat_id: chat, parse_mode: 'Markdown', disable_web_page_preview: true, text: msg ) rescue Telebot::Error => e raise CantPost, "#{e.}, can't post this message: \"#{msg}\"" end |
#run ⇒ Object
You can run a chat bot to listen to the messages coming to it, in a separate thread.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/telepost.rb', line 80 def run Telebot::Bot.new(@token).run do |chat, | if block_given? yield(chat, ) elsif !chat.nil? id = .chat.id if id.positive? post( .chat.id, "This is your chat ID: `#{.chat.id}`." ) end end end rescue Net::OpenTimeout retry end |
#spam(*lines) ⇒ Object
Send the message (lines will be concatenated with a space between them) to the chats provided in the constructor and encapsulated.
101 102 103 104 105 |
# File 'lib/telepost.rb', line 101 def spam(*lines) @chats.each do |chat| post(chat, lines) end end |