-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rb
1604 lines (1394 loc) · 58.7 KB
/
main.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'telegram/bot'
require 'net/http'
require 'json'
require 'httparty'
require 'nokogiri'
require 'uri'
require 'rss'
require 'google/apis/books_v1'
require 'googleauth'
require 'dotenv/load'
require 'goodreads'
require 'openlibrary'
require 'rest-client'
require 'json'
require 'uri'
require 'base64'
require 'google/apis/youtube_v3'
require 'date'
require 'sinatra'
require 'json'
require 'uri'
require 'net/http'
require 'cgi'
require 'rest-client'
require 'open-uri'
require 'openstreetmap'
require 'rmagick'
BIBLE_API_URL = 'https://api.scripture.api.bible/v1'
LeafletJS_URL = 'https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.js'
LeafletCSS_URL = 'https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.css'
def handle_use_scrape(bot, message)
bot.api.send_message(chat_id: message.chat.id, text: 'Please enter the URL to scrape:')
bot.listen do |response|
url = response.text.strip
webpage_content = scrape_webpage(url)
parsed_content = parse_html(webpage_content)
if parsed_content[:error]
bot.api.send_message(chat_id: message.chat.id, text: "Error scraping the webpage: #{parsed_content[:error]}")
else
response_text = "<b>#{parsed_content[:title]}</b>\n\n#{parsed_content[:content]}"
while response_text.length > 4096
bot.api.send_message(chat_id: message.chat.id, text: response_text.slice!(0, 4096), parse_mode: 'HTML')
end
bot.api.send_message(chat_id: message.chat.id, text: response_text, parse_mode: 'HTML')
end
end
end
def scrape_webpage(url)
response = RestClient.get("http://api.scraperapi.com", { params: { api_key: ENV['SCRAPERAPI_KEY'], url: url } })
response.body
rescue RestClient::ExceptionWithResponse => e
{ error: e.response }
end
def parse_html(content)
doc = Nokogiri::HTML(content)
title = doc.css('title').text.strip
main_content = ""
main_content << "## #{title}\n\n"
main_content << doc.css('h1, h2, h3, h4, p, ul, ol, a').map do |element|
case element.name
when 'h1'
"## #{element.text.strip}"
when 'h2'
"### #{element.text.strip}"
when 'h3'
"#### #{element.text.strip}"
when 'h4'
"##### #{element.text.strip}"
when 'p'
element.text.strip
when 'ul', 'ol'
element.css('li').map { |li| "* #{li.text.strip}" }.join("\n")
when 'a'
"[#{element.text.strip}](#{element['href']})"
else
element.text.strip
end
end.join("\n\n")
user_details = doc.css('.user-details').map(&:text).join("\n\n")
meta_description = doc.at('meta[name="description"]')['content'] rescue nil
meta_keywords = doc.at('meta[name="keywords"]')['content'] rescue nil
additional_content = ""
additional_content << "### User Details\n\n#{user_details}\n\n" unless user_details.empty?
additional_content << "### Meta Description\n\n#{meta_description}\n\n" if meta_description
additional_content << "### Meta Keywords\n\n#{meta_keywords}\n\n" if meta_keywords
main_content << additional_content
{ title: title, content: main_content.strip }
end
class OpenStreetMapClient
include HTTParty
base_uri 'https://nominatim.openstreetmap.org'
def search(query)
self.class.get('/search', query: { q: query, format: 'json', addressdetails: 1, limit: 1 }, headers: { 'User-Agent' => 'YourAppName/1.0 (your-email@example.com)' })
end
end
def handle_use_cohere(bot, message)
require 'telegram/bot'
require 'http'
require 'json'
require 'logger'
$logger = Logger.new(STDOUT)
$logger.level = Logger::DEBUG
def send_typing_action(bot, chat_id)
bot.api.send_chat_action(chat_id: chat_id, action: 'typing')
sleep(2)
end
def send_message_to_cohere(prompt)
cohere_url = 'https://api.cohere.ai/v1/generate'
headers = {
'Authorization' => "Bearer #{ENV['COHERE_API_KEY']}",
'Content-Type' => 'application/json'
}
payload = {
model: 'command-xlarge-nightly',
prompt: prompt,
max_tokens: 2048,
temperature: 1.0
}
response = HTTP.headers(headers).post(cohere_url, json: payload)
if response.status.success?
JSON.parse(response.body.to_s)
else
$logger.error "Cohere API request failed: #{response.status} - #{response.body}"
nil
end
rescue StandardError => e
$logger.error "Error sending message to Cohere: #{e.message}"
nil
end
def parse_cohere_response(response)
if response && response['generations'] && response['generations'].any?
response['generations'].first['text'].strip
else
"Sorry, I couldn't process your request."
end
end
Telegram::Bot::Client.run(ENV['TELEGRAM_BOT_TOKEN']) do |bot|
bot.listen do |message|
begin
case message
when Telegram::Bot::Types::Message
case message.text
when 'Ask Cohere anything'
bot.api.send_message(chat_id: message.chat.id, text: "Hello there! 👋 I'm an advanced AI assistant powered by Cohere, Ask me anything.")
else
send_typing_action(bot, message.chat.id)
bot.api.send_message(chat_id: message.chat.id, text: "One moment please, I'm processing your request... ⏳")
send_typing_action(bot, message.chat.id)
bot.api.send_message(chat_id: message.chat.id, text: "Be advised that responses might delay. 🕑 Please wait... ")
send_typing_action(bot, message.chat.id)
cohere_response = send_message_to_cohere(message.text)
if cohere_response
response_text = parse_cohere_response(cohere_response)
bot.api.send_message(chat_id: message.chat.id, text: response_text)
else
bot.api.send_message(chat_id: message.chat.id, text: "Sorry, I couldn't get a response from Cohere.")
end
send_typing_action(bot, message.chat.id)
sleep(2)
bot.api.send_message(chat_id: message.chat.id, text: "You can type /start to start again.")
end
end
rescue StandardError => e
$logger.error "Error processing message: #{e.message}"
bot.api.send_message(chat_id: message.chat.id, text: "Sorry, there was an error processing your request.")
end
end
end
end
def handle_use_CSE(bot, message)
require 'telegram/bot'
require 'google/apis/customsearch_v1'
$search_client = Google::Apis::CustomsearchV1::CustomSearchAPIService.new
$search_client.key = ENV['CUSTOM_SEARCH_API_KEY']
$search_active = false
def send_typing_action(bot, chat_id)
bot.api.send_chat_action(chat_id: chat_id, action: 'typing')
sleep(2)
end
def perform_google_search(bot, message, query)
send_typing_action(bot, message.chat.id)
start_index = 1
max_results = 15
results_count = 0
while results_count < max_results
results = $search_client.list_cses(q: query, cx: ENV['CUSTOM_SEARCH_CX'], num: 10, start: start_index)
items = results.items
break unless items
items.each_with_index do |item, index|
title = "<b>#{item.title}</b>"
link = item.link
snippet = item.snippet
image_url = find_thumbnail_for_item(item)
result_text = "#{results_count + 1}. #{title}\n#{snippet}\n#{link}"
send_typing_action(bot, message.chat.id)
bot.api.send_message(chat_id: message.chat.id, text: result_text, parse_mode: 'HTML')
if image_url
send_typing_action(bot, message.chat.id)
bot.api.send_photo(chat_id: message.chat.id, photo: image_url)
end
results_count += 1
break if results_count >= max_results
end
start_index += 10
break if results_count >= max_results
end
bot.api.send_message(chat_id: message.chat.id, text: "No more results found for '#{query}'") if results_count == 0
$search_active = false
end
def find_thumbnail_for_item(item)
return unless item.pagemap && item.pagemap['cse_thumbnail']
item.pagemap['cse_thumbnail'][0]['src']
end
Telegram::Bot::Client.run(ENV['TELEGRAM_BOT_TOKEN']) do |bot|
bot.listen do |message|
case message
when Telegram::Bot::Types::Message
case message.text
when 'Do a Custom Search'
$search_active = true
send_typing_action(bot, message.chat.id)
bot.api.send_message(chat_id: message.chat.id, text: "Please enter your search query.")
else
if $search_active
search_query = message.text
perform_google_search(bot, message, search_query)
else
send_typing_action(bot, message.chat.id)
bot.api.send_message(chat_id: message.chat.id, text: "Please type 'Do a Custom Search' to start a new search session.")
end
end
end
end
end
end
def handle_leave_a_message(bot, message)
whatsapp_number = 'Add Number here!'
whatsapp_link = "https://wa.me/#{whatsapp_number}"
bot.api.send_message(
chat_id: message.chat.id,
text: "Click the link below to redirect to WhatsApp \u{1F514}",
reply_markup: Telegram::Bot::Types::InlineKeyboardMarkup.new(
inline_keyboard: [
[
Telegram::Bot::Types::InlineKeyboardButton.new(
text: 'Go to WhatsApp',
url: whatsapp_link
)
]
]
)
)
end
def handle_use_map(bot, message)
mapclient = OpenStreetMapClient.new
def handle_start(bot, message)
reply_markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(
keyboard: [
[Telegram::Bot::Types::KeyboardButton.new(text: 'Use OpenStreetMap')]
],
one_time_keyboard: true
)
bot.api.send_message(chat_id: message.chat.id, text: "Welcome! Choose an option:", reply_markup: reply_markup)
end
def handle_location_search(bot, message, mapclient)
query = message.text
response = mapclient.search(query)
if response.code != 200
bot.api.send_message(chat_id: message.chat.id, text: "Sorry, there was an error processing your request.")
return
end
results = response.parsed_response
if results.empty?
bot.api.send_message(chat_id: message.chat.id, text: "Sorry, no location found for '#{query}'.")
else
location = results.first
location_name = location['display_name']
latitude = location['lat'].to_f
longitude = location['lon'].to_f
address = location['address'] || {}
road = address['road'] || 'N/A'
city = address['city'] || address['town'] || address['village'] || 'N/A'
state = address['state'] || 'N/A'
country = address['country'] || 'N/A'
postcode = address['postcode'] || 'N/A'
output_message = "**Location found:** #{location_name}\n\n"
output_message << "**Coordinates:**\n"
output_message << "Lat: **#{latitude}**, Lon: **#{longitude}**\n\n"
output_message << "**Address Details:**\n"
output_message << "Road: **#{road}**\n"
output_message << "City: **#{city}**\n"
output_message << "State: **#{state}**\n"
output_message << "Country: **#{country}**\n"
output_message << "Postcode: **#{postcode}**\n\n"
output_message << "[View on OpenStreetMap](https://www.openstreetmap.org/?mlat=#{latitude}&mlon=#{longitude})"
bot.api.send_message(chat_id: message.chat.id, text: output_message, parse_mode: 'Markdown')
end
end
def send_map(bot, chat_id, latitude, longitude, output_message)
begin
map_image = generate_map_image(latitude, longitude, output_message)
bot.api.send_photo(chat_id: chat_id, photo: map_image)
rescue => e
bot.api.send_message(chat_id: chat_id, text: "Error processing image: #{e.message}")
puts "Error processing image: #{e.message}"
end
end
def generate_map_image(latitude, longitude, message)
map_url = "https://www.openstreetmap.org/export/embed.html?bbox=#{longitude-0.05},#{latitude-0.05},#{longitude+0.05},#{latitude+0.05}&layer=mapnik"
file = URI.open(map_url)
image = Magick::Image.from_blob(file.read).first
draw = Magick::Draw.new
draw.annotate(image, 0, 0, 10, 10, message) do
draw.gravity = Magick::SouthGravity
draw.pointsize = 16
draw.stroke = 'black'
draw.fill = 'white'
draw.font_weight = Magick::BoldWeight
end
image.format = 'PNG'
image_blob = image.to_blob
file.close if file && !file.closed?
image_blob
end
def handle_message(bot, message, mapclient, session)
case session[:step]
when :awaiting_location
handle_location_search(bot, message, mapclient)
session[:step] = nil
else
case message.text
when 'Use Map'
# handle_start(bot, message)
# when 'Use OpenStreetMap'
bot.api.send_message(chat_id: message.chat.id, text: "Enter a location to search on OpenStreetMap (e.g., address, landmark):")
session[:step] = :awaiting_location
else
bot.api.send_message(chat_id: message.chat.id, text: "Please use /start to begin.")
end
end
end
sessions = Hash.new { |h, k| h[k] = {} }
Telegram::Bot::Client.run(ENV['TELEGRAM_BOT_TOKEN']) do |bot|
bot.listen do |message|
chat_id = message.chat.id
session = sessions[chat_id]
case message
when Telegram::Bot::Types::Message
handle_message(bot, message, mapclient, session)
end
end
end
end
def handle_use_bible(bot, message)
def send_main_menu(bot, chat_id)
kb = [
[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch All Available Bibles', callback_data: 'fetch_bibles')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch All Available Audio Bibles', callback_data: 'fetch_audio_bibles')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch Books for a Specific Bible', callback_data: 'fetch_books_for_bible')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch Books for a Specific Audio Bible', callback_data: 'fetch_books_for_audio_bible')],
[Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Search verses in Specific version', callback_data: 'search_verses')]
# [Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch All Passages in a Bible', callback_data: 'fetch_all_passages_for_bible')],
# [Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Fetch Chapters in a Book', callback_data: 'fetch_chapters_in_book')]
]
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb)
bot.api.send_message(chat_id: chat_id, text: 'Choose an option:', reply_markup: markup)
end
def fetch_bibles
url = "#{BIBLE_API_URL}/bibles"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
response.code == 200 ? JSON.parse(response.body)['data'] : nil
end
def fetch_search_results(bible_id, query)
url = "#{BIBLE_API_URL}/bibles/#{bible_id}/search"
params = { query: query }
headers = { 'api-key' => ENV['BIBLE_API_KEY'] }
begin
response = RestClient.get(url, headers: headers, params: params)
handle_search_results_response(response)
rescue RestClient::ExceptionWithResponse => e
handle_search_results_response(e.response)
rescue RestClient::Exception, StandardError => e
puts "Error fetching search results: #{e.message}"
nil
end
end
def handle_search_results_response(response)
case response.code
when 200
JSON.parse(response.body)['data']['results']
else
puts "Failed to fetch search results. HTTP #{response.code}: #{response.body}"
nil
end
rescue JSON::ParserError => e
puts "Error parsing JSON response: #{e.message}"
nil
end
def fetch_chapters(bible_id, book_id)
encoded_book_id = CGI.escape(book_id)
url = "#{BIBLE_API_URL}/v1/bibles/#{bible_id}/books/#{encoded_book_id}/chapters"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
if response.code == 200
JSON.parse(response.body)['data']
else
puts "Failed to fetch chapters. HTTP #{response.code}: #{response.body}"
nil
end
end
def send_chapters_list(bot, chat_id, chapters, bible_id, book_id, page = 1)
per_page = 20
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
chapters_slice = chapters[start_index..end_index]
if chapters_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch chapters. Please try again later.')
return
end
response_text = "*Chapters in this Book (Page #{page}):*\n\n"
chapters_slice.each do |chapter|
response_text += "*#{chapter['number']}* (#{chapter['id']})\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "chapter_page_#{bible_id}_#{book_id}_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "chapter_page_#{bible_id}_#{book_id}_#{page + 1}") if chapters.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
def fetch_all_passages(bible_id)
url = "#{BIBLE_API_URL}/bibles/#{bible_id}/passages"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
response.code == 200 ? JSON.parse(response.body)['data'] : nil
end
def fetch_audio_bible_books(audio_bible_id)
url = "#{BIBLE_API_URL}/audio-bibles/#{audio_bible_id}/books"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
response.code == 200 ? JSON.parse(response.body)['data'] : nil
end
def fetch_audio_bibles
url = "#{BIBLE_API_URL}/audio-bibles"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
response.code == 200 ? JSON.parse(response.body)['data'] : nil
end
def send_all_passages(bot, chat_id, passages, bible_id, page = 1)
per_page = 50
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
passages_slice = passages[start_index..end_index]
if passages_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch passages. Please try again later.')
return
end
response_text = "*Passages in this Bible (Page #{page}):*\n\n"
passages_slice.each do |passage|
response_text += "*#{passage['reference']}*\n#{passage['content']}\n\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "passage_page_#{bible_id}_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "passage_page_#{bible_id}_#{page + 1}") if passages.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
def send_audio_bible_books_list(bot, chat_id, books, audio_bible_id, page = 1)
per_page = 100
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
books_slice = books[start_index..end_index]
if books_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch books. Please try again later.')
return
end
response_text = "*Books in this Audio Bible (Page #{page}):*\n\n"
books_slice.each do |book|
response_text += "*#{book['name']}* (#{book['id']})\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "audio_book_page_#{audio_bible_id}_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "audio_book_page_#{audio_bible_id}_#{page + 1}") if books.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
def fetch_books(bible_id)
url = "#{BIBLE_API_URL}/bibles/#{bible_id}/books"
response = HTTParty.get(url, headers: { "api-key": ENV['BIBLE_API_KEY'] })
response.code == 200 ? JSON.parse(response.body)['data'] : nil
end
def send_books_list(bot, chat_id, books, bible_id, page = 1)
per_page = 100
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
books_slice = books[start_index..end_index]
if books_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch books. Please try again later.')
return
end
response_text = "*Books in this Bible (Page #{page}):*\n\n"
books_slice.each do |book|
response_text += "*#{book['name']}* (#{book['id']})\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "book_page_#{bible_id}_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "book_page_#{bible_id}_#{page + 1}") if books.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
def send_bibles_page(bot, chat_id, bibles, page)
per_page = 20
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
bibles_slice = bibles[start_index..end_index]
if bibles_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch bibles. Please try again later.')
return
end
response_text = "*Available Bibles (Page #{page}):*\n\n"
bibles_slice.each do |bible|
response_text += "*#{bible['name']}* (#{bible['id']})\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "page_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "page_#{page + 1}") if bibles.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
def send_audio_bibles_page(bot, chat_id, audio_bibles, page)
per_page = 20
start_index = (page - 1) * per_page
end_index = start_index + per_page - 1
audio_bibles_slice = audio_bibles[start_index..end_index]
if audio_bibles_slice.nil?
bot.api.send_message(chat_id: chat_id, text: 'Failed to fetch audio bibles. Please try again later.')
return
end
response_text = "*Available Audio Bibles (Page #{page}):*\n\n"
audio_bibles_slice.each do |audio_bible|
response_text += "*#{audio_bible['name']}* (#{audio_bible['id']})\n"
end
kb = []
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Previous', callback_data: "audio_page_#{page - 1}") if page > 1
kb << Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Next', callback_data: "audio_page_#{page + 1}") if audio_bibles.length > end_index + 1
markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb.each_slice(2).to_a)
bot.api.send_message(chat_id: chat_id, text: response_text, parse_mode: 'Markdown', reply_markup: markup)
end
user_states = {}
Telegram::Bot::Client.run(ENV['TELEGRAM_BOT_TOKEN']) do |bot|
bot.listen do |message|
case message
when Telegram::Bot::Types::Message
case message.text
when 'Use Bible'
# bot.api.send_chat_action(chat_id: message.chat.id, action: 'typing')
# sleep 2
# bot.api.send_message(chat_id: message.chat.id, text: "This is an experimental project. Be advised not all features are available.")
# sleep 2
send_main_menu(bot, message.chat.id)
else
if user_states[message.chat.id] == :waiting_for_bible_id_for_passages
bible_id = message.text.strip
passages = fetch_all_passages(bible_id)
if passages.nil?
bot.api.send_message(chat_id: message.chat.id, text: 'Failed to fetch passages for this Bible. Please try again later.')
else
send_all_passages(bot, message.chat.id, passages, bible_id)
end
user_states.delete(message.chat.id)
elsif user_states[message.chat.id] == :waiting_for_bible_id
bible_id = message.text.strip
books = fetch_books(bible_id)
if books.nil?
bot.api.send_message(chat_id: message.chat.id, text: 'Failed to fetch books for this Bible. Please try again later.')
else
send_books_list(bot, message.chat.id, books, bible_id)
end
user_states.delete(message.chat.id)
elsif user_states[message.chat.id] == :waiting_for_audio_bible_id
audio_bible_id = message.text.strip
books = fetch_audio_bible_books(audio_bible_id)
if books.nil?
bot.api.send_message(chat_id: message.chat.id, text: 'Failed to fetch books for this Audio Bible. Please try again later.')
else
send_audio_bible_books_list(bot, message.chat.id, books, audio_bible_id)
end
user_states.delete(message.chat.id)
elsif user_states[message.chat.id] == :waiting_for_bible_id_for_chapters
user_states[message.chat.id] = { state: :waiting_for_book_id_for_chapters, bible_id: message.text.strip }
bot.api.send_message(chat_id: message.chat.id, text: 'Please enter the Book ID:')
elsif user_states[message.chat.id].is_a?(Hash) && user_states[message.chat.id][:state] == :waiting_for_book_id_for_chapters
bible_id = user_states[message.chat.id][:bible_id]
book_id = message.text.strip
chapters = fetch_chapters(bible_id, book_id)
if chapters.nil?
bot.api.send_message(chat_id: message.chat.id, text: 'Failed to fetch chapters for this Book. Please try again later.')
else
send_chapters_list(bot, message.chat.id, chapters, bible_id, book_id)
end
user_states.delete(message.chat.id)
elsif user_states[message.chat.id] == :waiting_for_bible_id_for_search
bible_id = message.text.strip
bot.api.send_message(chat_id: message.chat.id, text: 'Please enter your search query:')
user_states[message.chat.id] = { state: :waiting_for_search_query, bible_id: bible_id }
elsif user_states[message.chat.id].is_a?(Hash) && user_states[message.chat.id][:state] == :waiting_for_search_query
query = message.text.strip
bible_id = user_states[message.chat.id][:bible_id]
results = fetch_search_results(bible_id, query)
if results.nil?
bot.api.send_message(chat_id: message.chat.id, text: 'Failed to fetch search results. Please try again later.')
else
send_search_results(bot, message.chat.id, results, bible_id, query)
end
end
end
when Telegram::Bot::Types::CallbackQuery
case message.data
when 'fetch_bibles'
bibles = fetch_bibles
if bibles.nil?
bot.api.send_message(chat_id: message.from.id, text: 'Failed to fetch bibles. Please try again later.')
else
send_bibles_page(bot, message.from.id, bibles, 1)
end
when /^page_(\d+)$/
page = Regexp.last_match(1).to_i
bibles = fetch_bibles
send_bibles_page(bot, message.from.id, bibles, page)
when 'fetch_audio_bibles'
audio_bibles = fetch_audio_bibles
if audio_bibles.nil?
bot.api.send_message(chat_id: message.from.id, text: 'Failed to fetch audio bibles. Please try again later.')
else
send_audio_bibles_page(bot, message.from.id, audio_bibles, 1)
end
when /^audio_page_(\d+)$/
page = Regexp.last_match(1).to_i
audio_bibles = fetch_audio_bibles
send_audio_bibles_page(bot, message.from.id, audio_bibles, page)
when 'fetch_books_for_bible'
bot.api.send_message(chat_id: message.from.id, text: 'Please enter the Bible ID:')
user_states[message.from.id] = :waiting_for_bible_id
when 'fetch_books_for_audio_bible'
bot.api.send_message(chat_id: message.from.id, text: 'Please enter the Audio Bible ID:')
user_states[message.from.id] = :waiting_for_audio_bible_id
when 'fetch_all_passages_for_bible'
bot.api.send_message(chat_id: message.from.id, text: 'Please enter the Bible ID:')
user_states[message.from.id] = :waiting_for_bible_id_for_passages
when 'fetch_chapters_in_book'
bot.api.send_message(chat_id: message.from.id, text: 'Please enter the Bible ID:')
user_states[message.from.id] = :waiting_for_bible_id_for_chapters
when 'search_verses'
bot.api.send_message(chat_id: message.from.id, text: 'Please enter the Bible ID:')
user_states[message.from.id] = :waiting_for_bible_id_for_search
when /^bible_(\w+)$/
bible_id = Regexp.last_match(1)
books = fetch_books(bible_id)
if books.nil?
bot.api.send_message(chat_id: message.from.id, text: 'Failed to fetch books for this Bible. Please try again later.')
else
send_books_list(bot, message.from.id, books, bible_id)
end
when /^book_page_(\w+)_(\d+)$/
bible_id = Regexp.last_match(1)
page = Regexp.last_match(2).to_i
books = fetch_books(bible_id)
send_books_list(bot, message.from.id, books, bible_id, page)
when /^audio_bible_(\w+)$/
audio_bible_id = Regexp.last_match(1)
books = fetch_audio_bible_books(audio_bible_id)
if books.nil?
bot.api.send_message(chat_id: message.from.id, text: 'Failed to fetch books for this Audio Bible. Please try again later.')
else
send_audio_bible_books_list(bot, message.from.id, books, audio_bible_id)
end
when /^audio_book_page_(\w+)_(\d+)$/
audio_bible_id = Regexp.last_match(1)
page = Regexp.last_match(2).to_i
books = fetch_audio_bible_books(audio_bible_id)
send_audio_bible_books_list(bot, message.from.id, books, audio_bible_id, page)
end
end
end
end
bot.api.send_message(chat_id: message.chat.id, text: "Implementing Bible functionality...")
end
def fetch_latest_news
rss_url = 'https://www.standardmedia.co.ke/rss/headlines.php'
begin
rss = RSS::Parser.parse(rss_url, false)
if rss && rss.items.any?
news_items = rss.items.take(5)
news_texts = []
news_items.each_with_index do |item, index|
title = item.title
link = item.link
guid = item.guid.content if item.guid
pub_date = item.pubDate.strftime("%Y-%m-%d %H:%M:%S") if item.pubDate
description = item.description if item.description
creator = item.dc_creator if item.dc_creator
news_text = "Article #{index + 1}:\n"
news_text += "Title: #{title}\n"
news_text += "GUID: #{guid}\n" if guid
news_text += "Published Date: #{pub_date}\n" if pub_date
news_text += "Description: #{description}\n" if description
news_text += "Link: #{link}\n"
news_text += "Creator: #{creator}\n" if creator
news_texts << news_text
end
return news_texts.join("\n\n")
else
return "Failed to fetch latest news from The Standard. No items found."
end
rescue StandardError => e
puts "Error fetching RSS feed: #{e.message}"
return "Failed to fetch latest news from The Standard. Please try again later."
end
end
def fetch_latest_kenyan_news
rss_url = 'https://www.standardmedia.co.ke/rss/kenya.php'
begin
rss_content = URI.open(rss_url).read
rss = RSS::Parser.parse(rss_content, false)
if rss && rss.items.any?
news_items = rss.items.take(5)
news_texts = []
news_items.each_with_index do |item, index|
title = item.title
link = item.link
guid = item.guid.content if item.guid
pub_date = item.pubDate.strftime("%Y-%m-%d %H:%M:%S") if item.pubDate
description = item.description if item.description
creator = item.dc_creator if item.dc_creator
news_text = "Article #{index + 1}:\n"
news_text += "Title: #{title}\n"
news_text += "GUID: #{guid}\n" if guid
news_text += "Published Date: #{pub_date}\n" if pub_date
news_text += "Description: #{description}\n" if description
news_text += "Link: #{link}\n"
news_text += "Creator: #{creator}\n" if creator
news_texts << news_text
end
return news_texts.join("\n\n")
else
return "Failed to fetch latest news from The Standard. No items found."
end
rescue StandardError => e
puts "Error fetching RSS feed: #{e.message}"
return "Failed to fetch latest Kenyan news from The Standard. Please try again later."
end
end
def fetch_latest_entertainment_news
rss_url = 'https://www.standardmedia.co.ke/rss/entertainment.php'
begin
rss = RSS::Parser.parse(rss_url, false)
if rss && rss.items.any?
news_items = rss.items.take(5)
news_texts = []
news_items.each_with_index do |item, index|
title = item.title
link = item.link
guid = item.guid.content if item.guid
pub_date = item.pubDate.strftime("%Y-%m-%d %H:%M:%S") if item.pubDate
description = item.description if item.description
creator = item.dc_creator if item.dc_creator
news_text = "Article #{index + 1}:\n"
news_text += "Title: #{title}\n"
news_text += "GUID: #{guid}\n" if guid
news_text += "Published Date: #{pub_date}\n" if pub_date
news_text += "Description: #{description}\n" if description
news_text += "Link: #{link}\n"
news_text += "Creator: #{creator}\n" if creator
news_texts << news_text
end
return news_texts.join("\n\n")
else
return "Failed to fetch latest news from The Standard. No items found."
end
rescue StandardError => e
puts "Error fetching RSS feed: #{e.message}"
return "Failed to fetch latest Entertainment news from The Standard. Please try again later."
end
end
class CheckOpenLibrary
BASE_URL = 'https://openlibrary.org'.freeze
RESULTS_LIMIT = 30
def search_books(author_name)
encoded_author = URI.encode_www_form_component(author_name)
url = "#{BASE_URL}/search.json?author=#{encoded_author}&limit=#{RESULTS_LIMIT}"
response = HTTParty.get(url)
if response.success?
parse_books(response)
else
puts "Error: #{response.code} - #{response.message}"
[]
end
rescue StandardError => e
puts "Error searching Open Library: #{e.message}"
[]
end
private
def parse_books(response)
data = response.parsed_response
if data && data['docs'].any?
books = data['docs'].map do |book|
{
title: book['title'],
author: Array(book['author_name']).join(', '),
link: "#{BASE_URL}#{book['key']}",
description: book['subtitle'] || 'No description available'
}
end
books
else
puts 'No books found.'
[]
end
end
end
def scrape_webpage(url)
response = RestClient.get("http://api.scraperapi.com", { params: { api_key: ENV['SCRAPERAPI_KEY'], url: url } })
response.body
rescue RestClient::ExceptionWithResponse => e
{ error: e.response }
end
def parse_html(content)
doc = Nokogiri::HTML(content)
title = doc.css('title').text.strip
main_content = ""
main_content << "## #{title}\n\n"
main_content << doc.css('h1, h2, h3, h4, p, ul, ol, a').map do |element|
case element.name
when 'h1'
"## #{element.text.strip}"
when 'h2'
"### #{element.text.strip}"
when 'h3'
"#### #{element.text.strip}"
when 'h4'
"##### #{element.text.strip}"
when 'p'
element.text.strip
when 'ul', 'ol'
element.css('li').map { |li| "* #{li.text.strip}" }.join("\n")
when 'a'
"[#{element.text.strip}](#{element['href']})"
else
element.text.strip
end
end.join("\n\n")
user_details = doc.css('.user-details').map(&:text).join("\n\n")
meta_description = doc.at('meta[name="description"]')['content'] rescue nil
meta_keywords = doc.at('meta[name="keywords"]')['content'] rescue nil
additional_content = ""
additional_content << "### User Details\n\n#{user_details}\n\n" unless user_details.empty?
additional_content << "### Meta Description\n\n#{meta_description}\n\n" if meta_description
additional_content << "### Meta Keywords\n\n#{meta_keywords}\n\n" if meta_keywords
main_content << additional_content
{ title: title, content: main_content.strip }
end
def get_access_token
url = "https://open-api.tiktok.com/oauth/access_token/"
response = HTTParty.post(url, body: {
# Ensure you create a TikTok app here: https://open.tiktok.com/developer/apps/ which will give you a client_key and client_secret.
client_key: 'XXXXXXXXXXXXXXXXXX',
client_secret: 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
grant_type: 'client_credentials'
})
if response.code == 200
response.parsed_response['access_token']
else
raise "Failed to get access token: #{response.code} - #{response.body}"
end
end
def get_user_info(username)
url = "https://open-api.tiktok.com/v1/user/@#{username}/"
headers = {
'Authorization' => "Bearer #{get_access_token}"