Current section

Files

Jump to
ex_gram lib ex_gram middleware ignore_username.ex
Raw

lib/ex_gram/middleware/ignore_username.ex

defmodule ExGram.Middleware.IgnoreUsername do
@moduledoc """
Middleware that strips the bot username from commands.
Transforms `/command@bot_username` to `/command` before the message is handled.
This is useful when your bot is used in group chats where commands may be
explicitly targeted at your bot to avoid ambiguity with other bots.
## Example
defmodule MyBot do
use ExGram.Bot, name: :my_bot
middleware ExGram.Middleware.IgnoreUsername
end
See the [Middlewares guide](middlewares.md) for more details.
"""
use ExGram.Middleware
alias ExGram.Cnt
def call(%Cnt{bot_info: %{username: username}, update: %{message: %{text: t} = message} = update} = cnt, _opts)
when is_binary(username) and is_binary(t) do
new_text = clean_command(t, username)
new_msg = %{message | text: new_text}
new_update = %{update | message: new_msg}
%{cnt | update: new_update}
end
def call(%Cnt{bot_info: %{username: username}, update: %{message: %{caption: t} = message} = update} = cnt, _opts)
when is_binary(username) and is_binary(t) do
new_caption = clean_command(t, username)
new_msg = %{message | caption: new_caption}
new_update = %{update | message: new_msg}
%{cnt | update: new_update}
end
def call(cnt, _), do: cnt
defp clean_command("/" <> text, username) do
[raw_command | rest] = String.split(text, ~r/\s/, parts: 2)
cmd =
case String.split(raw_command, "@") do
[command, ^username] -> "/" <> command
_ -> "/" <> raw_command
end
Enum.join([cmd | rest], " ")
end
defp clean_command(text, _username), do: text
end