Created
March 4, 2017 01:11
-
-
Save cronokirby/c2aae2e153ec9934dfcb7fc3ce06644a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Bot do | |
@moduledoc false | |
use Application | |
alias Alchemy.Client | |
def start(_, _) do | |
run = Client.start(@local, selfbot: "my_id") | |
use Eval | |
run | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Eval do | |
@moduledoc false | |
use Alchemy.Cogs | |
alias Alchemy.Embed | |
alias Alchemy.Client | |
import Alchemy.Embed | |
# evaluates code in a new process | |
defp evaluate(message, code) do | |
result = try do | |
{result, _} = Code.eval_string(code, [message: message], __ENV__) | |
result | |
rescue | |
e -> e | |
end | |
end | |
defp eval_embed(input, output) do | |
code_block = fn code -> | |
"```elixir\n" <> code <> "\n```" | |
end | |
%Embed{} | |
|> field("Input:", code_block.(input)) | |
|> field("Output:", code_block.(output)) | |
end | |
Cogs.set_parser(:eval, fn string -> | |
string | |
|> String.split(["```\n", "\n```"]) | |
|> Enum.drop(1) | |
end) | |
# waits 5s for a result | |
Cogs.def eval(code) do | |
task = Task.async(fn -> evaluate(message, code) end) | |
case Task.yield(task) || Task.shutdown(task) do | |
{:ok, result} -> | |
embed = eval_embed(code, Macro.to_string(result)) |> build | |
Client.edit_message(message, "", embed: embed) | |
nil -> | |
embed = eval_embed(code, "Process took over 5s to yield a result.") |> build | |
Client.edit_message(message, "", embed: embed) | |
end | |
end | |
Cogs.def eval, do: nil | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment