0

I have set up a chat settong using Pidgin and Ejabberd.I have written down a custom module in ejabberd using user_send_packet:

ejabberd_hooks:add(user_send_packet, _Host, ?MODULE,
           myMessage, 95),

The function myMessage is as follows:

myMessage({Packet, C2SState})->


PacketType=xmpp:get_name(Packet),
case PacketType of
<<"iq">>->
ok;
<<"presence">>->
ok;
<<"message">>->

Sum=2+2,
?INFO_MSG("Sum is ~p~n",[Sum])

end,

{Packet,C2SState}.

Basically what this function does is that whenever someone sends a chat message say "hello there", the value of Sum gets calculated and printed on the server and its logs and the message ""hello there" is sent to the second user.

But Now I want send the value of Sum along with the message "hello there" to the second user for example:

"hello there Sum is 4" 

Can anyone help me out with this?

Thanks in advance.

abhishek ranjan
  • 612
  • 7
  • 23

1 Answers1

1

Here it is:

process_message({#message{body = Body} = Msg, C2SState})->
    Sum = calc_sum_and_return_as_binary(),
    NewBody = lists:map(
        fun(#text{data = Data} = Txt) ->
            Txt#text{data = <<Data/binary, Sum/binary>>}
        end, Body),
    {Msg#message{body = NewBody}, C2SState};
process_message(Acc) ->
    Acc.

Note, that #text{} record contains lang field which can be used if you want to support internationalization of the text being appended.

user2610053
  • 516
  • 2
  • 7
  • Thank you for the reply first. I used the code snippet given by you and observed the following things:Firstly Sum=4 was not getting converted into binary since Sum is a variable, then I used Sum=[4] but the user to whom this message was sent closed the connection and restarted it with the message "Connection reset by peer". Then I tried Sum="4", Sum=["4"] and Sum ="[4]" which were all successful and sent the messages as 4,4 and [4] respectively.Then I have learnt that in erlang string is nothing but a list only so thinking that I used Sum=[[4]] but it went to the connection reset again. – abhishek ranjan Aug 03 '17 at 12:55
  • So I want to ask two things:(1)how can I send just Sum=[4] as a message to be received as [4] ? and (2) Is it neccessary to enclose each sending message under double inverted commas "" to be sent as a message? – abhishek ranjan Aug 03 '17 at 12:56
  • Look, these are simple Erlang questions, you're better off spending a couple of hours learning simple Erlang tutorial to clarify these things. – user2610053 Aug 03 '17 at 19:37
  • Simply put, if you want to append "[4]" text, you should do the following: Sum = list_to_binary([$[, integer_to_list(2+2), $]]) – user2610053 Aug 03 '17 at 19:39