james28909 has asked for the wisdom of the Perl Monks concerning the following question:
I am having some difficulty trying to understand how to reconnect this websocket. I have a simple discord bot that i am using to provide services to users at a website i moderate. Everything works as expected except when the gateway operation code '7' (server requests reconnect) is sent to my client. To reconnect/resume a connection, you must send session id, token and sequence number of the last event. I have all of this info already and am not to sure about how to reconnect/resume the websocket connection. I would ask at discord api chat but this isnt a discord problem, its a me not knowing how to reconnect with the lib i am using problem lol. EDIT: Before this code there are a POST and a GET request sent to their servers for authorization and logging the bot in. When i do this i get the session_id and token. those two values are stored in a %globals hash and accessed when needed to reconnect.
here is a snippet from my script:
my $ua = Mojo::UserAgent->new; $ua->inactivity_timeout(0); $ua->websocket( $gateway . ':443?v=9&application/json, text/plain, */*' => sub { my ( $ua, $tx ) = @_; # Check if WebSocket handshake was successful say 'WebSocket handshake failed!' and return unless $tx->is_we +bsocket; # Wait for WebSocket to be closed $tx->on( finish => sub { my ( $tx, $code, $reason ) = @_; say "WebSocket closed with status $code and $reason"; $ua->websocket->resume; #would i use the payload he +re somehow instead of using sub reconnect()? } ); $tx->on( message => sub { my ( $tx, $msg ) = @_; my $data = decode_json($msg); my %payload = %$data; $globals{'sequence'} = $payload{'s'} if defined $paylo +ad{'s'}; for ( $payload{'op'} ) { when ('7') { reconnect( $tx, %payload ) } } } ); } ); Mojo::IOLoop->start unless Mojo::IOLoop->is_running; sub reconnect { my $reconnect_payload = { op => 6, d => { token => $globals{'token'}, session_id => $globals{'session_id'}, seq => defined( $globals{'sequence'} ) ? $globals{ +'sequence'} : 'null' }, s => 'null', t => 'null' }; #how to reconnect }
The code is not a drop in place and work kind of thing. There could be syntax errors but hopefully this gets the point across of what i am trying to figure out. I just cant figure out how to reconnect.
here are links to their api reference and i am pretty sure i have the payload setup right, I just dont know how to reconnect this websocket when requested.
resume structure sent by client to server to reconnect
server op code payload structure
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: mojo::websocket reconnect
by alexander_lunev (Pilgrim) on May 19, 2022 at 20:43 UTC | |
by james28909 (Deacon) on May 23, 2022 at 07:15 UTC | |
by alexander_lunev (Pilgrim) on May 24, 2022 at 05:19 UTC | |
by james28909 (Deacon) on May 20, 2022 at 18:11 UTC |