Skip to content

Commit

Permalink
refactor + telegram api update
Browse files Browse the repository at this point in the history
  • Loading branch information
punkrelique committed Aug 18, 2024
1 parent 93a5697 commit a2ffcb9
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 66 deletions.
2 changes: 1 addition & 1 deletion src/Botinok.Common/Botinok.Common.fsproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/Botinok.Libgen/Botinok.Libgen.fsproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

Expand Down
30 changes: 15 additions & 15 deletions src/Botinok.Libgen/Parser.fs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@
open FSharp.Data
open Botinok.Libgen.Types

[<Literal>]
let private newLine = "\r\n"

let private getId (nodes: HtmlNode) =
nodes.TryGetAttribute("href")
|> Option.map (fun x -> x.Value())
|> Option.map (_.Value())
|> Option.defaultValue ""
|> fun x -> x.Split('=') |> Seq.last

Expand All @@ -25,29 +22,32 @@ let extractBooks content =
let name =
x[2].Descendants["a"]
|> Seq.head
|> fun x -> x.Elements() |> Seq.head |> (fun x -> x.InnerText())
|> fun x -> x.Elements() |> Seq.head |> (_.InnerText())

let isbn = x[2].Descendants() |> Seq.last |> (fun x -> x.InnerText())
let isbn = x[2].Descendants() |> Seq.last |> (_.InnerText())

let edition =
x[2].Descendants["font"]
|> Seq.toList
|> fun nodes -> if nodes.Length = 3 then nodes |> List.skip 1 else nodes
|> List.tryHead
|> Option.map (fun node -> node.InnerText())
|> Option.map (_.InnerText())
|> Option.defaultValue ""
|> fun text -> if (text = isbn || text = name) then "" else text

{ ISBN = isbn
Authors =

let authors =
x[1].Descendants()
|> Seq.toList
|> List.filter (fun node ->
match node with
| HtmlText text -> text <> newLine
| HtmlText text -> text <> "\r\n"
| _ -> false)
|> List.map (fun x -> x.InnerText())
|> List.map (_.InnerText())

let id = x[2].Descendants["a"] |> Seq.last |> getId

{ ISBN = isbn
Authors = authors
Name = name
Publisher = x[3].InnerText()
Edition = edition
Expand All @@ -56,18 +56,18 @@ let extractBooks content =
Language = x[6].InnerText()
Size = x[7].InnerText()
Extension = x[8].InnerText()
Id = x[2].Descendants["a"] |> Seq.last |> getId })
Id = id })

let extractLinksFromDownloadPage content =
HtmlDocument.Parse(content).Descendants["a"]
|> Seq.choose (fun x -> x.TryGetAttribute("href") |> Option.map (fun a -> a.Value()))
|> Seq.choose (fun x -> x.TryGetAttribute("href") |> Option.map (_.Value()))
|> Seq.take 4

let extractBook content =
let trs =
HtmlDocument.Parse(content).Descendants["table"]
|> Seq.head
|> fun x -> x.Elements()
|> _.Elements()

{ ISBN = (trs[7].Elements()[1]).InnerText()
Authors = (trs[2].Elements()[1]).InnerText().Split(',') |> Seq.toList
Expand Down
1 change: 0 additions & 1 deletion src/Botinok.Libgen/Types.fs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

open System.Web


type Genre =
| NonFiction
| Fiction
Expand Down
7 changes: 4 additions & 3 deletions src/Botinok/Botinok.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<Compile Include="Requests.fs" />
<Compile Include="Core.fs" />
<Compile Include="Commands\Other.fs" />
<Compile Include="Commands\Libgen.fs" />
Expand All @@ -22,8 +23,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Funogram" Version="2.0.7" />
<PackageReference Include="Funogram.Telegram" Version="6.7.0" />
<PackageReference Include="Funogram" Version="3.0.1" />
<PackageReference Include="Funogram.Telegram" Version="7.7.0" />
<PackageReference Remove="FSharp.Core" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />
Expand Down
2 changes: 1 addition & 1 deletion src/Botinok/Commands/Base.fs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ let wrap ctx fn =
let fromId () =
match ctx.Update.Message with
| Some msg -> msg.From.Value.Id
| None _ -> ctx.Update.CallbackQuery.Value.Message.Value.Chat.Id
| _ -> ctx.Update.CallbackQuery.Value.From.Id
fn ctx.Config (fromId())

let updateArrived (ctx: UpdateContext) =
Expand Down
70 changes: 26 additions & 44 deletions src/Botinok/Commands/Libgen.fs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module Botinok.Commands.Libgen

open Botinok
open Botinok.Libgen.Types
open Botinok.LibgenClient
open Funogram.Telegram
open Funogram.Telegram.Bot
open Funogram.Telegram.Types
open Botinok.Core
Expand Down Expand Up @@ -32,65 +32,50 @@ let private bookListMarkup (books: Book seq) book page =

keyboard

let private bookInfoTemplate (book: Book) =
let private bookInfoMarkup (book: Book) =
let markup = Markup.InlineKeyboardMarkup { InlineKeyboard = [|
[|
InlineKeyboardButton.Create("скачать", callbackData = $"book/download/{book.Id}")
|]
|] }

(book.ToString(), markup)

let private callbackMessageId (ctx: UpdateContext) = ctx.Update.CallbackQuery.Value.Message.Value.MessageId
let private commandMessageId (ctx: UpdateContext) = ctx.Update.Message.Value.MessageId

let private libgenClient = LibgenClient()

let searchBooks (book: string) (ctx: UpdateContext) config (chatId: int64) =
if book.Length < 3 then Req.SendMessage.Make(chatId, "длина запроса должна быть больше 2 символов", replyToMessageId = commandMessageId ctx) |> bot config
if book.Length < 3 then
Requests.sendReply chatId "длина запроса должна быть больше 2 символов" ctx |> bot config

let booksResult =
libgenClient.Search(SearchQuery.createDefaultQuery(book, 1))
|> Async.AwaitTask
|> Async.RunSynchronously

match booksResult with
| Ok books ->
Req.SendMessage.Make(
chatId,
$"\"{book}\"",
replyMarkup = Markup.InlineKeyboardMarkup { InlineKeyboard = bookListMarkup books book 1 },
replyToMessageId = commandMessageId ctx
)
|> bot config
| Error error ->
Req.SendMessage.Make(chatId, error, replyToMessageId = commandMessageId ctx)
|> bot config
| Ok books -> Requests.sendReplyMarkup
chatId
$"\"{book}\""
ctx
(Markup.InlineKeyboardMarkup { InlineKeyboard = bookListMarkup books book 1 })
|> bot config
| Error error -> Requests.sendReply chatId error ctx |> bot config

let downloadBook id (ctx: UpdateContext) config (chatId: int64) =
let bookResult =
libgenClient.DownloadBook id |> Async.AwaitTask |> Async.RunSynchronously
let bookResult = libgenClient.DownloadBook id |> Async.AwaitTask |> Async.RunSynchronously

match bookResult with
| Ok(file, name) ->
Req.SendDocument.Make(chatId, InputFile.File(name, file), replyToMessageId = callbackMessageId ctx)
|> bot config
| Error error ->
Req.SendMessage.Make(chatId, error, replyToMessageId = callbackMessageId ctx)
|> bot config
| Ok(file, name) -> Requests.sendDocument chatId name file ctx |> bot config
| Error error -> Requests.sendReply chatId error ctx |> bot config

let getBook id (ctx: UpdateContext) config (chatId: int64) =
let bookResult =
libgenClient.GetBook id |> Async.AwaitTask |> Async.RunSynchronously
let bookResult = libgenClient.GetBook id |> Async.AwaitTask |> Async.RunSynchronously

match bookResult with
| Ok book ->
let info, markup = bookInfoTemplate book
Req.SendMessage.Make(chatId, info, replyMarkup = markup, replyToMessageId = callbackMessageId ctx)
|> bot config
| Error error ->
Req.SendMessage.Make(chatId, error, replyToMessageId = callbackMessageId ctx)
|> bot config
let info, markup = bookInfoMarkup book
Requests.sendReplyMarkup chatId info ctx markup |> bot config
| Error error -> Requests.sendReply chatId error ctx |> bot config

let getAnotherPages book (page: string) (ctx: UpdateContext) config (chatId: int64) =
let page = int page
Expand All @@ -101,13 +86,10 @@ let getAnotherPages book (page: string) (ctx: UpdateContext) config (chatId: int
|> Async.RunSynchronously

match booksResult with
| Ok books ->
Req.EditMessageReplyMarkup.Make(
chatId = chatId,
messageId = callbackMessageId ctx,
replyMarkup = InlineKeyboardMarkup.Create(bookListMarkup books book page)
)
|> bot config
| Error error ->
Req.SendMessage.Make(chatId = chatId, text = error, replyToMessageId = callbackMessageId ctx)
|> bot config
| Ok books -> Requests.editMessageReplyMarkup
chatId
ctx
(InlineKeyboardMarkup.Create(bookListMarkup books book page))
|> bot config
| Error error -> Requests.sendReply chatId error ctx |> bot config

2 changes: 2 additions & 0 deletions src/Botinok/Program.fs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ open Funogram.Telegram.Bot
open Botinok
open Funogram.Api
open Funogram.Telegram
open Funogram.Telegram.Types
open Microsoft.Extensions.Configuration
open Serilog

Expand Down Expand Up @@ -31,6 +32,7 @@ let main _ =
|> logInfo

let! _ = Api.deleteWebhookBase () |> api botConfig

return! startBot botConfig Commands.Base.updateArrived None
}
|> Async.RunSynchronously
Expand Down
25 changes: 25 additions & 0 deletions src/Botinok/Requests.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module Botinok.Requests

open Funogram.Telegram
open Funogram.Telegram.Bot
open Funogram.Telegram.Types

let private getMessageId (ctx: UpdateContext) =
match ctx.Update.Message with
| Some msg -> msg.MessageId
| _ ->
match ctx.Update.CallbackQuery.Value.Message.Value with
| Message m -> m.MessageId
| InaccessibleMessage im -> im.MessageId

let sendReply (chatId: int64) msg ctx =
Req.SendMessage.Make(chatId, msg, replyParameters = ReplyParameters.Create(messageId = getMessageId ctx))

let sendReplyMarkup (chatId: int64) msg ctx markup =
Req.SendMessage.Make(chatId, msg, replyParameters = ReplyParameters.Create(messageId = getMessageId ctx), replyMarkup = markup)

let editMessageReplyMarkup (chatId: int64) (ctx: UpdateContext) markup =
Req.EditMessageReplyMarkup.Make(chatId = ChatId.Int chatId, messageId = getMessageId ctx, replyMarkup = markup)

let sendDocument (chatId: int64) filename file ctx =
Req.SendDocument.Make(chatId, InputFile.File(filename, file), replyParameters = ReplyParameters.Create(messageId = getMessageId ctx))

0 comments on commit a2ffcb9

Please sign in to comment.