使用Erlang从ejabberd发送消息

时间:2015-04-23 06:37:45

标签: erlang xmpp ejabberd

我有简单的ejabebrd插件,我需要从它发送消息。我发布了我的代码示例和错误,我得到了。请给我你的反馈意见。

我的代码:

-module(mod_final).
-on_load(send_message/0).
-behaviour(gen_mod).
-export([start/2, stop/1]).

-include("ejabberd.hrl").
-include("logger.hrl").
-include("jlib.hrl").

start(_Host, _Opt) ->
        ?INFO_MSG("mod_final starting", []),
        ok.

stop(_Host) ->
    ?INFO_MSG("mod_final stoping", []),
        ok.

send_message() ->
    LUser = "test1",
    LServer = "localhost",
    From = jlib:make_jid(LUser, LServer, []),

    TUser = "test2",
    TServer = "localhost",
    To = jlib:make_jid(TUser, TServer, []),

    FromAddress = jlib:jid_to_string(From),
    ToAddress = jlib:jid_to_string(To),

    ?INFO_MSG("send message starting", []),

    XmlBody = {xmlelement, "message", [{"id", []},{"type", "chat"}, {"from", FromAddress}, {"to", ToAddress}], [{xmlelement, "body", [], [{xmlcdata, <<"Test Message">>}]}]},

   ejabberd_router:route(From, To, XmlBody).

但我收到了这个错误:

   D(<0.252.0>:ejabberd_router:313) : route
    from {jid,"test1","localhost",[],"test1",
                  "localhost",[]}
    to {jid,"test2","localhost",[],"test2",
                "localhost",[]}
    packet {xmlelement,"message",
                   [{"type","error"},
                    {"to","test2@localhost"},
                    {"from","test1@localhost"},
                    {"id",[]}],
                   [{xmlelement,"body",[],[{xmlcdata,<<"Test Message">>}]},
                    {xmlelement,"error",
                        [{"code","503"},{"type","cancel"}],
                        [{xmlelement,"service-unavailable",
                             [{"xmlns","urn:ietf:params:xml:ns:xmpp-stanzas"}],
                             []}]}]}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我的建议是不要创建自己的XML。您可以使用此函数捕获数据包,然后写入错误日志

on_filter_packet({From, To, XML} = Packet) ->
    %% does something with a packet
    %% should return modified Packet or atom `drop` to drop the packet

    error_logger:info_msg(XML, [a_module]),

    %% or use error_logger:info_msg(xml:get_subtag(XML, <<"body">>), [a_module]),
    %% to take a body
    Packet.

然后你可以使用相同的xml,但改变了xmlcdata