Skip to content

Commit

Permalink
Add group id filtering for Telegram (#85)
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Oct 19, 2019
1 parent 3502000 commit d200895
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 32 deletions.
24 changes: 16 additions & 8 deletions Emulsion.Tests/SettingsTests.fs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module Emulsion.Tests.SettingsTests

open System
open System.IO
open System.Threading.Tasks

open FSharp.Control.Tasks
open Microsoft.Extensions.Configuration
Expand All @@ -10,7 +10,8 @@ open Xunit
open Emulsion
open Emulsion.Settings

let private testConfigText = @"{
let private testConfigText groupIdLiteral =
sprintf @"{
""xmpp"": {
""login"": ""login"",
""password"": ""password"",
Expand All @@ -19,12 +20,12 @@ let private testConfigText = @"{
},
""telegram"": {
""token"": ""token"",
""groupId"": ""groupId""
""groupId"": %s
},
""log"": {
""directory"": ""/tmp/""
}
}"
}" <| groupIdLiteral

let private testConfiguration = {
Xmpp = {
Expand All @@ -35,24 +36,31 @@ let private testConfiguration = {
}
Telegram = {
Token = "token"
GroupId = "groupId"
GroupId = 200600L
}
Log = {
Directory = "/tmp/"
}
}

let private mockConfiguration() =
let private mockConfiguration groupIdLiteral =
let path = Path.GetTempFileName()
task {
do! File.WriteAllTextAsync(path, testConfigText)
do! File.WriteAllTextAsync(path, testConfigText groupIdLiteral)
return ConfigurationBuilder().AddJsonFile(path).Build()
}


[<Fact>]
let ``Settings read properly`` () =
task {
let! configuration = mockConfiguration()
let! configuration = mockConfiguration "200600"
Assert.Equal(testConfiguration, Settings.read configuration)
}

[<Fact>]
let ``Settings read the group id as string``(): Task<unit> =
task {
let! configuration = mockConfiguration "\"200600\""
Assert.Equal(testConfiguration, Settings.read configuration)
}
23 changes: 20 additions & 3 deletions Emulsion.Tests/Telegram/FunogramTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ open Xunit

open Emulsion
open Emulsion.Telegram
open Emulsion.Telegram.Funogram

let private selfUserId = 100500L
let private groupId = 200600L

let private createUser username firstName lastName = {
Id = 0L
Expand All @@ -16,9 +20,15 @@ let private createUser username firstName lastName = {
LanguageCode = None
}

let private currentChat = {
defaultChat with
Id = groupId
}

let private createMessage from text : Funogram.Types.Message =
{ defaultMessage with
From = from
Chat = currentChat
Text = text }

let private createReplyMessage from text replyTo : Funogram.Types.Message =
Expand All @@ -28,12 +38,14 @@ let private createReplyMessage from text replyTo : Funogram.Types.Message =
let private createForwardedMessage from (forwarded: Funogram.Types.Message) =
{ defaultMessage with
From = Some from
Chat = currentChat
ForwardFrom = forwarded.From
Text = forwarded.Text }

let private createStickerMessage from emoji =
{ defaultMessage with
From = Some from
Chat = currentChat
Sticker = Some {
FileId = ""
Width = 0
Expand Down Expand Up @@ -62,14 +74,13 @@ let private createEntities t offset length url = Some <| seq {
yield createEntity t offset length url
}


let private originalUser = createUser (Some "originalUser") "" None
let private replyingUser = createUser (Some "replyingUser") "" None
let private forwardingUser = createUser (Some "forwardingUser") "" None

module ReadMessageTests =
let selfUserId = 100500L
let readMessage = Funogram.MessageConverter.read selfUserId
let readMessageOpt = MessageConverter.read { SelfUserId = selfUserId; GroupId = groupId }
let readMessage = readMessageOpt >> Option.get

[<Fact>]
let readMessageWithUnknownUser() =
Expand Down Expand Up @@ -269,6 +280,12 @@ module ReadMessageTests =
readMessage reply
)

[<Fact>]
let messageFromOtherChatShouldBeIgnored(): unit =
let message = { createMessage (Some originalUser) (Some "test") with
Chat = defaultChat }
Assert.Equal(None, readMessageOpt message)

module FlattenMessageTests =
let private flattenMessage = Funogram.MessageConverter.flatten Funogram.MessageConverter.DefaultQuoteSettings
let private flattenMessageLineLimit limit =
Expand Down
14 changes: 8 additions & 6 deletions Emulsion/EmulsionSettings.fs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ type XmppSettings =
Room : string
Nickname : string }

type TelegramSettings =
{ Token : string
GroupId : string }
type TelegramSettings = {
Token: string
GroupId: int64
}

type LogSettings = {
Directory: string
Expand All @@ -28,9 +29,10 @@ let read (config : IConfiguration) : EmulsionSettings =
Password = section.["password"]
Room = section.["room"]
Nickname = section.["nickname"] }
let readTelegram (section : IConfigurationSection) =
{ Token = section.["token"]
GroupId = section.["groupId"] }
let readTelegram (section : IConfigurationSection) = {
Token = section.["token"]
GroupId = int64 section.["groupId"]
}
let readLog(section: IConfigurationSection) = {
Directory = section.["directory"]
}
Expand Down
43 changes: 29 additions & 14 deletions Emulsion/Telegram/Funogram.fs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ module MessageConverter =
linePrefix: string
}

type ReadMessageContext = {
SelfUserId: int64
GroupId: int64
}

let DefaultQuoteSettings = {
limits = {
messageLengthLimit = Some 500
Expand Down Expand Up @@ -192,16 +197,19 @@ module MessageConverter =
let messageText = text.Substring messageTextOffset
{ author = authorName; text = messageText }

let internal read (selfUserId: int64) (message: FunogramMessage): TelegramMessage =
let mainMessage = extractMessageContent message
match message.ReplyToMessage with
| None -> { main = mainMessage; replyTo = None }
| Some replyTo ->
let replyToMessage =
if isSelfMessage selfUserId replyTo
then extractSelfMessageContent replyTo
else extractMessageContent replyTo
{ main = mainMessage; replyTo = Some replyToMessage }
let internal read (context: ReadMessageContext) (message: FunogramMessage): TelegramMessage option =
if message.Chat.Id <> context.GroupId
then None
else
let mainMessage = extractMessageContent message
match message.ReplyToMessage with
| None -> Some { main = mainMessage; replyTo = None }
| Some replyTo ->
let replyToMessage =
if isSelfMessage context.SelfUserId replyTo
then extractSelfMessageContent replyTo
else extractMessageContent replyTo
Some { main = mainMessage; replyTo = Some replyToMessage }

let private processResultWithValue (logger: ILogger) (result: Result<'a, ApiResponseError>) =
match result with
Expand All @@ -213,12 +221,19 @@ let private processResultWithValue (logger: ILogger) (result: Result<'a, ApiResp
let private processResult logger (result: Result<'a, ApiResponseError>) =
processResultWithValue logger result |> ignore

let private updateArrived (logger: ILogger) onMessage (ctx: UpdateContext) =
let private updateArrived groupId (logger: ILogger) onMessage (ctx: UpdateContext) =
let readContext: MessageConverter.ReadMessageContext = {
SelfUserId = ctx.Me.Id
GroupId = groupId
}
processCommands ctx [
fun (msg, _) ->
logger.Information("Incoming Telegram message: {Message}", msg)
onMessage (TelegramMessage(MessageConverter.read ctx.Me.Id msg)); true
] |> ignore
match MessageConverter.read readContext msg with
| Some m -> onMessage(TelegramMessage m)
| None -> logger.Warning "Message from unidentified source ignored"
true
] |> ignore

let internal prepareHtmlMessage { author = author; text = text }: string =
sprintf "<b>%s</b>\n%s" (Html.escape author) (Html.escape text)
Expand All @@ -240,4 +255,4 @@ let run (logger: ILogger)
(onMessage: IncomingMessage -> unit): unit =
// TODO[F]: Update Funogram and don't ignore the cancellation token here.
let config = { defaultConfig with Token = settings.Token }
Bot.startBot config (updateArrived logger onMessage) None
Bot.startBot config (updateArrived settings.GroupId logger onMessage) None
2 changes: 1 addition & 1 deletion emulsion.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
},
"telegram": {
"token": "999999999:aaaaaaaaaaaaaaaaaaaaaaaaa_777777777",
"groupId": "12312312312"
"groupId": 12312312312
},
"log": {
"directory": "./logs/"
Expand Down

0 comments on commit d200895

Please sign in to comment.