forked from KrauseFx/mood
-
Notifications
You must be signed in to change notification settings - Fork 1
/
telegram_handler.rb
246 lines (209 loc) Β· 10.3 KB
/
telegram_handler.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
require_relative './database'
require 'telegram/bot'
require 'tempfile'
require 'gruff'
module Mood
class TelegramHandler
def self.custom_moods_keyboard(chatid)
#Inline keyboard default - see https://core.telegram.org/bots/api/#inlinekeyboardbutton
kb = [
[Telegram::Bot::Types::InlineKeyboardButton.new(text: '5: pumped, energized π₯', callback_data: '5'),
Telegram::Bot::Types::InlineKeyboardButton.new(text: '4: happy, excited π', callback_data: '4')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: '3: good, alright π', callback_data: '3'),
Telegram::Bot::Types::InlineKeyboardButton.new(text: '2: down, worried π', callback_data: '2')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: '1: Sad, unhappy π', callback_data: '1'),
Telegram::Bot::Types::InlineKeyboardButton.new(text: '0: Miserable, nervous π«', callback_data: '0')],
]
Mood::Database.database[:moodlabels].where(:chat_id => chatid).each do |n|
mood = n[:mood].to_i
label = n[:label].to_s
kb[((5 - mood)/2).to_i][(mood+1) % 2 ] = Telegram::Bot::Types::InlineKeyboardButton.new(text:"#{mood}: #{label}", callback_data: mood)
end
return Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb)
end
def self.send_question(message:)
self.perform_with_bot do |bot|
for chat in Mood::Database.database[:chats].all
this_chatid = chat[:chat_id]
begin
bot.api.send_message(
chat_id: this_chatid,
text: message,
reply_markup: self.custom_moods_keyboard(this_chatid)
)
rescue => ex
puts "error sending the mood question"
puts chat_id
puts ex
end
end
end
end
def self.send_message(message:)
success_count = 0
error_count = 0
self.perform_with_bot do |bot|
for chat in Mood::Database.database[:chats].all
this_chatid = chat[:chat_id]
begin
bot.api.send_message(
chat_id: this_chatid,
text: message
)
success_count = success_count + 1
rescue
error_count = error_count + 1
end
end
end
return success_count, error_count
end
def self.listen
self.perform_with_bot do |bot|
bot.listen do |message|
case message
when Telegram::Bot::Types::CallbackQuery
user_input = message.data
this_chat_id = message.from.id
bot.api.answerCallbackQuery({
'callback_query_id' => message.id
});
bot.api.deleteMessage({
'chat_id' => message.from.id,
'message_id' => message.message.message_id
});
when Telegram::Bot::Types::Message
user_input = message.text
this_chat_id = message.chat.id
end
begin
if user_input.to_s.to_i > 0 || user_input.to_s.strip.start_with?("0")
# As 0 is also a valid value
rating = user_input.to_i
if rating >= 0 && rating <= 5
Mood::Database.database[:moods].insert({
time: Time.now,
chat_id: this_chat_id,
value: rating
})
bot.api.send_message(chat_id: this_chat_id, text: "Got it ("+rating.to_s+")! It's marked in the books π")
if rating <= 1
bot.api.send_message(chat_id: this_chat_id, text: "Feeling down sometimes is okay. Maybe take 2 minutes to reflect on why you're not feeling better, and optionally add a /note")
bot.api.send_message(chat_id: this_chat_id, text: "Sending hugs π€π€π€")
end
if rating == 5
bot.api.send_message(chat_id: this_chat_id, text: "π« Awesome to hear, maybe take 2 minutes to reflect on why you're feeling great, and optionally add a /note")
end
else
bot.api.send_message(chat_id: this_chat_id, text: "Only values from 0 to 5 are allowed")
end
else
self.handle_input(bot, message)
end
rescue
# Do nothing
end
end
end
end
def self.handle_input(bot, message)
case message.text
# when "/stats"
# avg = Mood::Database.database[:moods].where(:chat_id => message.chat.id).avg(:value).to_f.round(2)
# total_moods = Mood::Database.database[:moods].where(:chat_id => message.chat.id).count
# first_mood = Mood::Database.database[:moods].where(:chat_id => message.chat.id).first[:time]
# number_of_months = (Time.now - first_mood) / 60.0 / 60.0 / 24.0 / 30.0
# average_number_of_moods = (total_moods / number_of_months) / 30.0
# bot.api.send_message(chat_id: message.chat.id, text: "The average mood is: #{avg}")
# bot.api.send_message(chat_id: message.chat.id, text: "Total tracked moods: #{total_moods}")
# bot.api.send_message(chat_id: message.chat.id, text: "Number of months tracked: #{number_of_months.round(1)}")
# bot.api.send_message(chat_id: message.chat.id, text: "Averaging #{average_number_of_moods.round(1)} per day")
when "/start"
bot.api.send_message(chat_id: message.chat.id, reply_markup: self.custom_moods_keyboard(message.chat.id), text: "πββοΈ Welcome to feelike! πββοΈ\n\nI will help you keep track of your mood.\nThree times a day I will ask you how do you feel at the moment.\nYou can use my special moods keyboard or just type in a 0-5 number (5 being the happiest).\n\nWhen you want to see your progress just send me '/graph'\nIf you'd lke to customize your mood options send '/setlabel'\nGot feedback? Please share! Type '/feedback your message'\n\nπ¦\n\nSo let's give it a try! how do you feel like right now?")
when "/mood"
bot.api.send_message(chat_id: message.chat.id, reply_markup: self.custom_moods_keyboard(message.chat.id), text: "How do you feel like? Share your mood")
when "/feedback"
bot.api.send_message(chat_id: message.chat.id, text: "To send us feedback type '/feedback your message'")
when /\/feedback\ /
feedback_content = message.text.split("/feedback ").last
user_desc = "#{message.from.first_name} #{message.from.last_name} #{message.from.username} (#{message.from.id})"
bot.api.send_message(chat_id: '-331527650', text: "#{user_desc.split.join(' ')}: #{feedback_content}")
bot.api.send_message(chat_id: message.chat.id, text: "Thanks for your feedback! We love hearing from our users β€οΈ")
when "/setlabel"
bot.api.send_message(chat_id: message.chat.id, text: "To set a mood's label use format: '/setlabel # Mood label'\nFor example '/setlabel 5 I'm on fire!! π₯'")
when /\/setlabel\ /
label_content = message.text.split("/setlabel ").last
label_mood = label_content[0]
label_text = label_content[2,label_content.length - 1]
if (label_mood=="0" or label_mood=="1" or label_mood=="2" or label_mood=="3" or label_mood=="4" or label_mood=="5")
previous_label = Mood::Database.database[:moodlabels].where(:chat_id => message.chat.id, :mood => label_mood)
previous_label.delete
Mood::Database.database[:moodlabels].insert({
chat_id: message.chat.id,
mood: label_mood,
label: label_text
})
bot.api.send_message(chat_id: message.chat.id, reply_markup: self.custom_moods_keyboard(message.chat.id), text: "Mood label set!")
else
bot.api.send_message(chat_id: message.chat.id, text: "Mood number must be between 0 and 5. Use the format '/setlabel # Mood label'")
end
when "/graph"
file = Tempfile.new("graph")
file_path = "#{file.path}.png"
moods = Mood::Database.database[:moods].where(:chat_id => message.chat.id)
g = Gruff::Line.new
g.title = "Your mood"
g.hide_legend = true
g.no_data_message = "There is no data"
g.reference_lines[:minimum] = { :value => 0, :color => "red" }
g.reference_lines[:maximum] = { :value => 5, :color => "green" }
# g.reference_lines[:horiz_one] = { :index => 1, :color => 'green' }
labels_arr = moods.each_with_index.map { |m,i| [i, m[:time]] }
g.labels = labels_arr.to_h
g.data(:mood, moods.collect { |m| m[:value] })
g.write(file_path)
bot.api.send_photo(
chat_id: message.chat.id,
photo: Faraday::UploadIO.new(file_path, 'image/png')
)
when "/notes"
Mood::Database.database[:notes].where(:chat_id => message.chat.id).each do |n|
bot.api.send_message(chat_id: message.chat.id, text: "#{n[:time].strftime("%Y-%m-%d")}: #{n[:note]}")
end
when /\/note\ /
note_content = message.text.split("/note ").last
Mood::Database.database[:notes].insert({
time: Time.at(message.date),
chat_id: message.chat.id,
note: note_content
})
bot.api.send_message(chat_id: message.chat.id, text: "Got it! I'll forever remember this note for you π")
else
bot.api.send_message(chat_id: message.chat.id, text: "Sorry, I don't understand what you're saying, #{message.from.first_name}")
end
end
def self.perform_with_bot
# https://github.com/atipugin/telegram-bot-ruby
yield self.client
rescue => ex
puts "error sending the telegram notification"
puts ex
puts ex.backtrace
end
def self.client
return @client if @client
raise "No Telegram token provided on `TELEGRAM_TOKEN`" if token.to_s.length == 0
@client = ::Telegram::Bot::Client.new(token)
end
def self.add_chat_id(chat_id)
begin
Mood::Database.database[:chats].insert(:chat_id => chat_id)
rescue
# Do nothing
end
end
def self.token
ENV["TELEGRAM_TOKEN"]
end
end
end