sharklib 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c681fcb5412d1bb557ca2e11b8c3f58f70feba64bb0e861ce270df1adba13512
4
+ data.tar.gz: '094969e357902a019b3b30b773b49a1750abc2bd7dedecc42687f9c2082e35a7'
5
+ SHA512:
6
+ metadata.gz: 50ba32e2cf8d26c1eb36f72448602429abe89f922747e615b3454c11e78d97d55406319558e57190641b273ed0d1c764fa3e049b8f39241736384407a728752b
7
+ data.tar.gz: ae7af3975d64e6f15a66099d9bbddf4b1ef1dc8c863473f6e64c254ce7af830c1460f480ec387206e703d5d8c6a9d966f7546d515160e5c1fd55c22853d106a1
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 staticgram.top/master
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
data/README.md ADDED
@@ -0,0 +1,4 @@
1
+ staticgram.top/master
2
+ staticgram.top/sharklib
3
+
4
+ В будущем появится полноценная документация на Github.
@@ -0,0 +1,258 @@
1
+ require 'uri'
2
+ require 'net/http'
3
+ require 'json'
4
+
5
+ module SharkLib
6
+ class Bot
7
+ attr_reader :commands
8
+ def initialize(token)
9
+ @token = token
10
+ @commands = {}
11
+ @messages = []
12
+ @business_messages = []
13
+ @callbacks = {}
14
+ @checkouts = {}
15
+ @offset = 0
16
+ @waiters = {}
17
+ @waiters_mutex = Mutex.new
18
+ end
19
+
20
+ def request(method, params={})
21
+ uri = URI("https://api.staticgram.top/bot#{@token}/#{method}")
22
+ http = Net::HTTP.new(uri.host, uri.port)
23
+ http.use_ssl = true
24
+
25
+ request = Net::HTTP::Post.new(uri)
26
+ request["Content-Type"] = "application/json"
27
+ request.body = params.to_json
28
+
29
+ response = http.request(request)
30
+
31
+ JSON.parse(response.body)
32
+ rescue JSON::ParserError
33
+ { "ok" => false, "error" => "Сервер вернул не JSON ответ." }
34
+ end
35
+
36
+ def get_updates
37
+ request("getUpdates", { offset: @offset, timeout: 30 })
38
+ end
39
+
40
+ ERRORS = {
41
+ "BUSINESS_PEER_USAGE_MISSING" => "Скорее всего, чат с человеком был неактивен длительное время.",
42
+ "BUTTON_INVALID" => "Кнопка вызвана неправильно."
43
+ }
44
+
45
+ def log_error(result)
46
+ return if result["ok"]
47
+ desc = (result["description"] || result["error"]).to_s
48
+ key = ERRORS.keys.find { |k| desc.include?(k) }
49
+ prefix = key || "ERROR"
50
+ puts "[!] #{prefix}: #{key ? ERRORS[key] : desc} -- #{result['error_code']}"
51
+ end
52
+
53
+ # --- Реестер ---
54
+ def on_command(command, &block)
55
+ cmd = "/#{command.to_s.delete_prefix('/')}"
56
+ @commands[cmd] = block
57
+ end
58
+
59
+ def on_message(&block)
60
+ @messages << block
61
+ end
62
+
63
+ def on_business_message(&block)
64
+ @business_messages << block
65
+ end
66
+
67
+ def on_callback(callback_data, &block)
68
+ @callbacks[callback_data] = block
69
+ end
70
+
71
+ def on_checkout(payload = nil, &block)
72
+ @checkouts[payload] = block
73
+ end
74
+
75
+ # --- Прочее ---
76
+ def register_waiter(key, queue)
77
+ @waiters_mutex.synchronize do
78
+ @waiters[key] = queue
79
+ end
80
+ end
81
+
82
+ def remove_waiter(key)
83
+ @waiters_mutex.synchronize { @waiters.delete(key) }
84
+ end
85
+
86
+ # --- Методы ---
87
+ def send_message(chat_id, text, **kwargs)
88
+ params = {
89
+ chat_id: chat_id,
90
+ text: text
91
+ }.merge(kwargs)
92
+
93
+ result = request("sendMessage", params)
94
+ log_error(result)
95
+ result
96
+ end
97
+
98
+ def edit_message(text, **kwargs)
99
+ params = {
100
+ text: text
101
+ }.merge(kwargs)
102
+
103
+ result = request("editMessageText", params)
104
+ log_error(result)
105
+ result
106
+ end
107
+
108
+ def delete_message(message_id, **kwargs)
109
+ params = {
110
+ message_id: message_id
111
+ }.merge(kwargs)
112
+
113
+ result = request("deleteMessage", params)
114
+ log_error(result)
115
+ result
116
+ end
117
+
118
+ def send_invoice(chat_id, title, description, payload, currency, prices, **kwargs)
119
+ params = {
120
+ chat_id: chat_id,
121
+ title: title,
122
+ description: description,
123
+ payload: payload,
124
+ currency: currency,
125
+ prices: prices
126
+ }.merge(kwargs)
127
+
128
+ result = request("sendInvoice", params)
129
+ log_error(result)
130
+ result
131
+ end
132
+
133
+ def answer_callback_query(callback_query_id, text: nil, show_alert: false, **kwargs)
134
+ params = {
135
+ callback_query_id: callback_query_id,
136
+ text: text,
137
+ show_alert: show_alert
138
+ }.merge(kwargs).compact
139
+
140
+ result = request("answerCallbackQuery", params)
141
+ log_error(result)
142
+ result
143
+ end
144
+
145
+ def answer_checkout_query(pre_checkout_query_id, ok: true, error_message:nil)
146
+ params = {
147
+ pre_checkout_query_id: pre_checkout_query_id,
148
+ ok: ok,
149
+ error_message: error_message
150
+ }
151
+
152
+ result = request("answerPreCheckoutQuery", params)
153
+ log_error(result)
154
+ result
155
+ end
156
+
157
+ def withdraw_gram(**kwargs)
158
+ result = request("withdrawGramBalance", **kwargs)
159
+ log_error(result)
160
+ result
161
+ end
162
+
163
+ def withdraw_star(**kwargs)
164
+ result = request("withdrawStarBalance", **kwargs)
165
+ log_error(result)
166
+ result
167
+ end
168
+
169
+ def get_user_gifts(user_id, **kwargs)
170
+ params = {
171
+ user_id: user_id
172
+ }.merge(kwargs)
173
+ result = request("getUserGifts", params)
174
+ log_error(result)
175
+ result
176
+ end
177
+
178
+ # --- Запуск ---
179
+ def run
180
+ puts "Привет #{'@SharkLib'.cyan}!"
181
+ loop do
182
+ update = get_updates
183
+
184
+ # puts JSON.pretty_generate(update) # для вывода всех апдейтов
185
+
186
+ if update["ok"] && update["result"]
187
+ update["result"].each do |data|
188
+
189
+ @offset = data["update_id"] + 1
190
+
191
+ Thread.new do
192
+ begin
193
+ ctx = Context.new(data, self)
194
+
195
+
196
+ if ctx.message&.text
197
+ waiter_key = [ctx.chat_id, ctx.sender_id]
198
+ waiter_queue = @waiters_mutex.synchronize { @waiters.delete(waiter_key) }
199
+ if waiter_queue
200
+ cmd = ctx.message.text&.split&.first
201
+ if cmd && @commands.key?(cmd)
202
+ waiter_queue << :cancelled
203
+ @commands[cmd].call(ctx)
204
+ else
205
+ waiter_queue << { text: ctx.message.text, message_id: ctx.message.id }
206
+ end
207
+ next
208
+ end
209
+
210
+ cmd = ctx.message.text&.split&.first
211
+ if cmd && @commands.key?(cmd)
212
+ @commands[cmd].call(ctx)
213
+ elsif ctx.business?
214
+ @business_messages.each do |handler|
215
+ handler.call(ctx)
216
+ end
217
+ else @messages
218
+ @messages&.each do |handler|
219
+ handler.call(ctx)
220
+ end
221
+ end
222
+ end
223
+ if ctx.callback_query
224
+ waiter_key = [ctx.chat_id, ctx.sender_id]
225
+ waiter_queue = @waiters_mutex.synchronize { @waiters.delete(waiter_key) }
226
+ waiter_queue << :cancelled if waiter_queue
227
+
228
+ cb_data = ctx.callback_query["data"].to_s
229
+
230
+ block = @callbacks[cb_data]
231
+
232
+ unless block
233
+ match = @callbacks.find do |callback_data, _|
234
+ callback_data.is_a?(Regexp) && callback_data.match?(cb_data)
235
+ end
236
+
237
+ block = match&.last
238
+ end
239
+ block.call(ctx) if block
240
+ end
241
+ if ctx.checkout_query
242
+ payload = ctx.checkout_query.invoice_payload
243
+ block = @checkouts[payload] || @checkouts[nil]
244
+ block.call(ctx) if block
245
+ end
246
+ rescue => e
247
+ puts e.message
248
+ end
249
+ end
250
+ end
251
+ end
252
+ rescue StandardError => e
253
+ puts "[!] Ошибка: что-то пошло не так во время запуска -- #{e}"
254
+ sleep 5
255
+ end
256
+ end
257
+ end
258
+ end
@@ -0,0 +1,13 @@
1
+ module SharkLib
2
+ class Chat
3
+ attr_reader :id, :type, :title, :username, :description
4
+
5
+ def initialize(data)
6
+ @id = data["id"]
7
+ @type = data["type"]
8
+ @title = data["title"]
9
+ @username = data["username"]
10
+ @description = data["description"]
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,13 @@
1
+ module SharkLib
2
+ class CheckoutQuery
3
+ attr_reader :id, :from, :currency, :total_amount, :invoice_payload
4
+
5
+ def initialize(data)
6
+ @id = data["id"]
7
+ @from = data["from"] ? User.new(data["from"]) : nil
8
+ @currency = data["currency"]
9
+ @total_amount = data["total_amount"]
10
+ @invoice_payload = data["invoice_payload"]
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,177 @@
1
+ module SharkLib
2
+ class Context
3
+ attr_reader :bot, :user, :message, :update, :callback_query, :checkout_query, :business_connection_id, :input_message_id
4
+
5
+ alias_method :from, :user
6
+ def initialize(data, bot)
7
+ @bot = bot
8
+ @update = data # Для спецефичных данных
9
+
10
+ if data["message"]
11
+ @message = Message.new(data["message"], bot)
12
+ @user = @message.from
13
+
14
+ elsif data["business_message"]
15
+ @message = Message.new(data["business_message"], bot)
16
+ @user = @message.from
17
+ @business_connection_id = data["business_message"]["business_connection_id"]
18
+
19
+ elsif data["callback_query"]
20
+ @callback_query = data["callback_query"]
21
+ @user = User.new(@callback_query["from"]) if @callback_query["from"]
22
+
23
+ if @callback_query["message"]
24
+ @message = Message.new(@callback_query["message"], bot)
25
+ end
26
+
27
+ elsif data["pre_checkout_query"]
28
+ @checkout_query = CheckoutQuery.new(data["pre_checkout_query"])
29
+ @user = @checkout_query.from
30
+ end
31
+ end
32
+
33
+ # --- специальные штуки ---
34
+ def business?
35
+ !@business_connection_id.nil?
36
+ end
37
+
38
+ def message_id
39
+ @message&.id
40
+ end
41
+
42
+ # --- Сокращения ---
43
+ def chat_id
44
+ @message&.chat&.id || @user&.id
45
+ end
46
+
47
+ def text
48
+ @message&.text
49
+ end
50
+
51
+ def emoji_id
52
+ @message&.emoji_id
53
+ end
54
+
55
+ def entities
56
+ @message&.entities
57
+ end
58
+
59
+ def sender_id
60
+ @user&.id
61
+ end
62
+
63
+ def username
64
+ @user&.username
65
+ end
66
+
67
+ # --- Методы ---
68
+ def answer(text, **kwargs)
69
+ return unless chat_id
70
+ kwargs[:business_connection_id] = @business_connection_id if @business_connection_id
71
+ res = @bot.send_message(chat_id, text, **kwargs)
72
+ Message.new(res["result"]) if res["ok"] && res["result"]
73
+ end
74
+
75
+ def reply(text, **kwargs)
76
+ return puts "[!] @message пуст" unless @message
77
+ kwargs[:business_connection_id] = @business_connection_id if @business_connection_id
78
+ res = @bot.send_message(chat_id, text, reply_to_message_id: @message.id, **kwargs)
79
+ Message.new(res["result"]) if res["ok"]
80
+ end
81
+
82
+ def edit_message(text, **kwargs)
83
+ return puts "[!] @message пуст" unless @message
84
+ if text.nil? || text.to_s.strip.empty? || text.is_a?(Array)
85
+ return puts "[!] Текст пуст"
86
+ end
87
+
88
+ kwargs[:business_connection_id] = @business_connection_id if @business_connection_id
89
+ kwargs[:chat_id] ||= @message.chat.id
90
+ kwargs[:message_id] ||= @message.id
91
+ @bot.edit_message(text, **kwargs)
92
+ end
93
+
94
+ def delete_message(message_id, **kwargs)
95
+ return puts "[!] @message пуст" unless @message
96
+ kwargs[:business_connection_id] = @business_connection_id if @business_connection_id
97
+ kwargs[:chat_id] ||= @message.chat.id
98
+ @bot.delete_message(message_id, **kwargs)
99
+ end
100
+
101
+ def answer_callback(text = nil, show_alert: false, **kwargs)
102
+ return puts "[!] @callback_query пуст" unless @callback_query
103
+ @bot.answer_callback_query(@callback_query["id"], text: text, show_alert: show_alert, **kwargs)
104
+ end
105
+
106
+ def answer_checkout(ok: true, error_message: nil)
107
+ return puts "[!] @checkout_query пуст" unless @checkout_query
108
+ @bot.answer_checkout_query(@checkout_query.id, ok: ok, error_message: error_message)
109
+ end
110
+
111
+ def inline_keyboard(&block)
112
+ InlineMarkup.build(&block)
113
+ end
114
+
115
+ def button(text, **kwargs)
116
+ InlineMarkup.button(text, **kwargs)
117
+ end
118
+
119
+ def send_invoice(chat_id, title, description, payload, currency, prices, **kwargs)
120
+ @bot.send_invoice(chat_id, title, description, payload, currency, prices, **kwargs)
121
+ end
122
+
123
+ def withdraw_gram(**kwargs)
124
+ @bot.withdraw_gram(**kwargs)
125
+ end
126
+
127
+ def withdraw_star(**kwargs)
128
+ @bot.withdraw_star(**kwargs)
129
+ end
130
+
131
+ def get_user_gifts(user_id, **kwargs)
132
+ @bot.get_user_gifts(user_id, **kwargs)
133
+ end
134
+
135
+ def input(text = nil, edit: false, timeout: nil, **kwargs)
136
+ if text
137
+ if edit
138
+ edit_message(text, **kwargs)
139
+ else
140
+ answer(text, **kwargs)
141
+ end
142
+ end
143
+
144
+ key = [chat_id, sender_id]
145
+ queue = Queue.new
146
+ @bot.register_waiter(key, queue)
147
+
148
+ result =
149
+ if timeout
150
+ timeout_end = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
151
+ loop do
152
+ unless queue.empty?
153
+ break queue.pop
154
+ end
155
+
156
+ remaining = timeout_end - Process.clock_gettime(Process::CLOCK_MONOTONIC)
157
+ if remaining <= 0
158
+ @bot.remove_waiter(key)
159
+ break nil
160
+ end
161
+
162
+ sleep([remaining, 0.05].min)
163
+ end
164
+ else
165
+ queue.pop
166
+ end
167
+ return nil if result.nil? || result == :cancelled
168
+
169
+ if result.is_a?(Hash)
170
+ @input_message_id = result[:message_id]
171
+ return result[:text]
172
+ end
173
+
174
+ result
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,36 @@
1
+ module SharkLib
2
+ class InlineMarkup
3
+ def initialize
4
+ @rows = []
5
+ end
6
+
7
+ def self.validate(url)
8
+ unless url.start_with?("https://")
9
+ raise ArgumentError, "[!] Only https:// scheme supported."
10
+ end
11
+ end
12
+
13
+ def row(*buttons)
14
+ @rows << buttons.flatten
15
+ self
16
+ end
17
+
18
+ def self.button(text, **kwargs)
19
+ if kwargs[:url]
20
+ validate(kwargs[:url])
21
+ end
22
+
23
+ { text: text }.merge(kwargs)
24
+ end
25
+
26
+ def to_h
27
+ { inline_keyboard: @rows }
28
+ end
29
+
30
+ def self.build
31
+ markup = new
32
+ yield(markup)
33
+ markup.to_h
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,20 @@
1
+ module SharkLib
2
+ class Message
3
+ attr_reader :from, :chat_id, :chat, :text, :id, :emoji_id, :entities
4
+
5
+ def initialize(data, bot = nil)
6
+ @bot = bot
7
+ @from = data["from"] ? User.new(data["from"]) : nil
8
+ @chat_id = data["chat"]["id"]
9
+ @chat = data["chat"] ? Chat.new(data["chat"]) : nil
10
+ @text = data["text"]
11
+ @id = data["message_id"]
12
+
13
+ emoji_entity = data["entities"]&.find { |e| e["type"] == "custom_emoji" }
14
+ @emoji_id = emoji_entity ? emoji_entity["custom_emoji_id"] : nil
15
+
16
+ @entities = data["entities"] || []
17
+ end
18
+ end
19
+ end
20
+
@@ -0,0 +1,12 @@
1
+ module SharkLib
2
+ class User
3
+ attr_reader :id, :username, :first_name, :last_name
4
+
5
+ def initialize(data)
6
+ @id = data["id"]
7
+ @username = data["username"]
8
+ @first_name = data["first_name"]
9
+ @last_name = data["last_name"]
10
+ end
11
+ end
12
+ end
data/lib/sharklib.rb ADDED
@@ -0,0 +1,9 @@
1
+ require "colorize"
2
+ require_relative "sharklib/bot"
3
+ require_relative "sharklib/user"
4
+ require_relative "sharklib/message"
5
+ require_relative "sharklib/chat"
6
+ require_relative "sharklib/inlinemarkup"
7
+ require_relative "sharklib/checkoutquery"
8
+ require_relative "sharklib/context"
9
+
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sharklib
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - staticgram.top/master
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: colorize
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.0'
26
+ description: 'Проект не планируется стать масштабным, библиотека обновляется. Автор:
27
+ staticgram.top/master Канал: staticgram.top/sharklib'
28
+ email:
29
+ - g0v@keemail.me
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - LICENSE.txt
35
+ - README.md
36
+ - lib/sharklib.rb
37
+ - lib/sharklib/bot.rb
38
+ - lib/sharklib/chat.rb
39
+ - lib/sharklib/checkoutquery.rb
40
+ - lib/sharklib/context.rb
41
+ - lib/sharklib/inlinemarkup.rb
42
+ - lib/sharklib/message.rb
43
+ - lib/sharklib/user.rb
44
+ licenses:
45
+ - MIT
46
+ metadata: {}
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 4.0.20
62
+ specification_version: 4
63
+ summary: Библиотека для BotAPI в мессенджере на отдельном MTProto сервере – Staticgram
64
+ test_files: []