97

The Stack Exchange WebSockets are handy for various things (like handling spam). For example, try running this JavaScript in your browser's console:

var w = new WebSocket("ws://qa.sockets.stackexchange.com/"); 
w.onmessage = function(e) { 
    data = JSON.parse(e.data)
    data.data = JSON.parse(data.data)
    console.log(data) 
}; 
w.onopen = function() { 
    w.send("155-questions-active") 
};

You'll then see a live feed of all questions on Stack Exchange right in your console! (click images to enlarge)

screenshot

screenshot

(155 means Stack Exchange. For another example, 3 means Super User.) However, this is only for questions. 155-posts-active and 155-answers-active don't seem to work.

(All the information in this post so far was figured out by ManishEarth; I give all credit to him ;))


So, how do the WebSockets work? Is there any way to get them to send all active answers, or even better, all active posts? What are all the IDs for the sites? How do the chat WebSockets work? etc.

15
  • I guess we could find out the IDs by experimentation, but experimentation has already failed us. Commented Feb 1, 2014 at 18:21
  • 41
    I hope the devs realize that if they don't tell us, we'll just write scripts to try things :P
    – Undo
    Commented Feb 1, 2014 at 18:25
  • 2
    Or we could just scrape the website or batch up to 100 requests per api call Commented Feb 1, 2014 at 18:30
  • 1
    I don't think you can count on the websockets API to be stable. There is a public API that is documented and supported, which also means that changes to the API take longer to manage. It could well be that it's not in the devs interest to document the websockets for public use. Commented Feb 1, 2014 at 18:33
  • 2
    @MartijnPieters in which case we are left with two other options: scrape every site (even if through the API) periodically (very expensive) or let the smaller communities drown in spam (undesirable) Commented Feb 1, 2014 at 18:42
  • 6
    @MartijnPieters All we really need is to know the websocket call for active network posts - it would really help in fighting spam, etc. Basically, we either let the small communities take care of themselves (which we don't want to do), we pound the API (expensive for both parties), or we get the websocket API call. We're not making a consumer-facing app, we'd just like to make a thing to help the network. So it doesn't need to be stable, just stable enough for us to be able to react to it. I hope I'm making sense ;)
    – Undo
    Commented Feb 1, 2014 at 18:46
  • 2
    in other words, we don't mind the order of arguments being changed once per six to eight weeks, but it would be nice if we are told about it nevertheless. Commented Feb 1, 2014 at 18:55
  • Nothing happens when I put those lines in my console.. I must be doing it wrong..
    – ɥʇǝS
    Commented Feb 2, 2014 at 3:59
  • 2
    @ɥʇǝS You've got to wait 15 seconds or so for questions to pop up. What browser are you using?
    – Doorknob
    Commented Feb 2, 2014 at 4:03
  • I tried it in Chromium and Firefox.
    – ɥʇǝS
    Commented Feb 2, 2014 at 4:03
  • @DoorknobofSnow Nothing happens.. I don't know what I might have done wrong..
    – ɥʇǝS
    Commented Feb 2, 2014 at 18:44
  • Now I got something i.imgur.com/2Z29Xk5.png but it doesn't look right.
    – ɥʇǝS
    Commented Feb 2, 2014 at 18:48
  • 1
    @ɥʇǝS You have to paste it all in; not line by line.
    – Doorknob
    Commented Feb 2, 2014 at 19:11
  • Ahhh. That makes much more sense.
    – ɥʇǝS
    Commented Feb 2, 2014 at 19:16
  • The example is not so easy to get running with Firefox (v. 63.0.3) and NoScript. (In Firefox, the browser console is started by menu ToolsWeb DeveloperWeb Console.) Commented Dec 2, 2018 at 17:28

5 Answers 5

82

Websocket-endpoints

(wss://qa.sockets.stackexchange.com)

  • <userid>-topbar: User topbar.

  • <userid>-inbox: User inbox/achievements

  • <siteid>-<userid>-reputation: User's rep on a site

  • <siteid>-home-active: Socket for homepage updates

  • <siteid>-questions-newest: For the "newest" page (only new questions)

  • <siteid>-questions-newest-tag-<tagname>: Newest for a specific tag

  • <siteid>-questions-active-tag-<tagname>: Active for a specific tag

  • <siteid>-question-<questionid>: Updates for a question

  • <siteid>-review-dashboard-update: For /review. Updates the dashboard, I guess

  • <siteid>-suggested-edits-count-update: Seems to update the suggested edits count. Don't know which count, haven't seen it in the wild yet.

  • 155-questions-active: Realtime tab

Notice that you can unsubscribe from an event by prepending a single dash.
For example send -155-questions-active to unsubscribe from events from the real-time tab. See also Is there a way to reset the qa.sockets.stackexchange.com web sockets?

Websocket format:

JSON string:

{
  "action": "", // endpoint that triggered this ws frame
  "data":"" // stringified data returned, in JSON. Yes, stringified, you have to JSON.parse() this string to get the data object.
}

The data format is different for each endpoint. Not going to list everything here, too lazy to find out.

Meanwhile, every 5 minutes the server will send a message with "action": "hb" and an empty data. Here hb stands for "heartbeat". You should respond with hb so the server will keep the websocket alive.

Sites

Some examples: 151 is Physics, 89 is AU, 3 is SU, 41 is Arqade, Meta Stack Exchange is 4.

You can parse this page with your favorite HTML parser (like BeautifulSoup or regular expressions) to fetch the ID of any site.

Chat

(wss://chat.sockets.stackexchange.com/events/<roomnumber>/<somehash>?l=<timethingy>)

The hash can be fetched by POSTing the room id and fkey to http://chat.stackexchange.com/ws-auth

The timethingy is the time key of the json returned by /chats/<roomnumber>/events.

No endpoints. Returns data of the form (this is very similar to the /events POST endpoint in chat, though that is a bit more confusing)

{
    "r89": { //some room you're in
        "e": [{
            "event_type": ,// event type 1=message posted. Not sure what the others mean
            "time_stamp": , 
            "content": "", //Message content. Can be html.
            "id": 3864139, // Websocket event id? Not sure
            "user_id": ,
            "user_name": "",
            "room_id": ,
            "room_name": "",
            "message_id": 
        }],
        "t": 3864139, // Websocket event id?
        "d": 1
    },
    "r139": { // some other room you're in. Suspect it will get filled with an events array
        "t": 3864139,
        "d": 1
    },
    "r551": { //some other room you're in
        "t": 3864139,
        "d": 1
    }
}
11
  • The chat event types seem to be hardcoded as local variables in master-chat.js; unfortunately, in the minified version, they're just listed as g=1; o=2; r=3; l=4; ma=5; z=6; H=7; j=8; n=9; m=10; ea=11; y=12; na=13; q=14; P=15; R=16; p=17; k=18; s=19; i=20; S=21; N=22; Q=29; da=30;. You wouldn't happen to know a URL for the unminified version, would you? Commented May 30, 2014 at 10:26
  • 1
    @IlmariKaronen I do. programmers.blogoverflow.com/2013/07/… (eg cdn-dev.sstatic.net/js/full.js) Commented May 30, 2014 at 16:00
  • Awesome! Except... I can find master-chat.js on the dev CDN, but it's still minified. :-( Commented May 30, 2014 at 16:06
  • @IlmariKaronen I've looked everywhere for unminified chat js. Never found any :/ Commented May 30, 2014 at 16:17
  • > The timethingy is the time key of the json returned by /chats/<roomno>/events. What is the complete url? I tried chat.stackexchange.com/chats/1/events it gived a 404
    – caub
    Commented Mar 20, 2015 at 0:39
  • @Manishearth When you say "POSTing the room id and fkey" do you mean posting {"roomId": 1, "fkey": <fkey>} gist.github.com/cauburtin/83359b45a783aadb500c?
    – caub
    Commented Mar 20, 2015 at 18:35
  • 2
    It's useful to note that {userid}-topbar refers to your userid on stackexchange.com, while {siteid}-{userid}-{reputation} refers to the userid on that particular site (and no, they're not the same, unfortunately). For example, on stackoverflow.com, I see: 1-563532-reputation and 272446-topbar
    – ert
    Commented Feb 16, 2016 at 2:52
  • 2
    Do these still work? 155-questions-active works for me but 1-questions-active and 155-questions-newest and 1-questions-newest do not. Commented Mar 22, 2017 at 22:10
  • "The hash can be fetched by POSTing the room id and fkey to chat.stackexchange.com/ws-auth" That requires you have the cookie set, that's no easy task. Commented Aug 1, 2018 at 5:35
  • What does action hb mean? I found this code but don't know what it's for. Commented Dec 1, 2018 at 13:14
  • 4
    @ɪBᴜɢ that is heartbeat. You're supposed to respond to it when you receive it so the server will keep the websocket alive.
    – rene Mod
    Commented Dec 2, 2018 at 11:43
28

Sites

These are the site IDs I've found so far, by running a script that grabs new questions' site IDs and watching the realtime ID, matching the titles.

Meta sites don't appear in realtime, so my strategy for finding them is that since generally the meta sites IDs are close to their parent sites' IDs, I just look through the metas of the sites near the ID until I find the question.

All site IDs (including metas) are available in JSON format via /topbar/site-switcher/all-pinnable-sites (you can find it if you hunt through full.en.js), which returns an array of the following objects, one per site:

 {  
    "title":"3d printing meta",
    "description":"",
    "sitename":"3D Printing Meta",
    "hostname":"3dprinting.meta.stackexchange.com",
    "siteid":641
 },

You can send these like __-questions-active, as mentioned in @ManishEarth's answer.

  1 Stack Overflow
  2 Server Fault
  3 Super User
  4 Meta Stack Exchange
 11 Area 51
 34 Web Applications
 36 Web Applications Meta
 41 Arqade
 42 Arqade Meta
 45 Webmasters
 46 Webmasters Meta
 49 Seasoned Advice
 50 Seasoned Advice Meta
 53 Game Development
 54 Game Development Meta
 61 Photography
 62 Photography Meta
 65 Cross Validated
 66 Cross Validated Meta
 69 Mathematics
 70 Mathematics Meta
 73 Home Improvement
 74 Home Improvement Meta
 77 Meta Super User
 78 Meta Server Fault
 79 Geographic Information Systems
 80 Geographic Information Systems Meta
 85 TeX - LaTeX
 87 TeX - LaTeX Meta
 89 Ask Ubuntu
 91 Ask Ubuntu Meta
 93 Personal Finance & Money
 95 Personal Finance & Money Meta
 97 English Language & Usage
 99 English Language & Usage Meta
101 Stack Apps
102 User Experience
104 User Experience Meta
106 Unix & Linux
108 Unix & Linux Meta
110 WordPress Development
112 WordPress Development Meta
114 Theoretical Computer Science
116 Theoretical Computer Science Meta
118 Ask Different
120 Ask Different Meta
122 Role-playing Games
124 Role-playing Games Meta
126 Bicycles
128 Bicycles Meta
131 Software Engineering
133 Software Engineering Meta
135 Electrical Engineering
137 Electrical Engineering Meta
139 Android Enthusiasts
141 Android Enthusiasts Meta
147 Board & Card Games
149 Board & Card Games Meta
151 Physics
153 Physics Meta
156 Homebrewing
158 Homebrewing Meta
162 Information Security
164 Information Security Meta
166 Writing
168 Writing Meta
170 Video Production
172 Video Production Meta
174 Graphic Design
176 Graphic Design Meta
182 Database Administrators
184 Database Administrators Meta
186 Science Fiction & Fantasy
188 Science Fiction & Fantasy Meta
194 Area 51 Discussions
196 Code Review
198 Code Review Meta
200 Code Golf
202 Code Golf Meta
204 Quantitative Finance
206 Quantitative Finance Meta
208 Project Management
210 Project Management Meta
212 Skeptics
214 Skeptics Meta
216 Physical Fitness
218 Physical Fitness Meta
220 Drupal Answers
222 Drupal Answers Meta
224 Motor Vehicle Maintenance & Repair
226 Motor Vehicle Maintenance & Repair Meta
228 Parenting
230 Parenting Meta
232 SharePoint
234 SharePoint Meta
240 Music: Practice & Theory
242 Music: Practice & Theory Meta
244 Software Quality Assurance & Testing
246 Software Quality Assurance & Testing Meta
248 Mi Yodeya
250 Mi Yodeya Meta
253 German Language
255 German Language Meta
257 Japanese Language
259 Japanese Language Meta
265 Philosophy
267 Philosophy Meta
269 Gardening & Landscaping
271 Gardening & Landscaping Meta
273 Travel
275 Travel Meta
281 Cryptography
283 Cryptography Meta
295 Signal Processing
297 Signal Processing Meta
299 French Language
301 French Language Meta
304 Christianity
306 Christianity Meta
308 Bitcoin
310 Bitcoin Meta
312 Linguistics
314 Linguistics Meta
320 Biblical Hermeneutics
322 Biblical Hermeneutics Meta
324 History
326 History Meta
336 Bricks
338 Bricks Meta
353 Spanish Language
355 Spanish Language Meta
363 Computational Science
365 Computational Science Meta
367 Movies & TV
369 Movies & TV Meta
371 Chinese Language
373 Chinese Language Meta
375 Biology
377 Biology Meta
379 Poker
381 Poker Meta
387 Mathematica
389 Mathematica Meta
391 Psychology & Neuroscience
393 Psychology & Neuroscience Meta
395 The Great Outdoors
397 The Great Outdoors Meta
403 Martial Arts
405 Martial Arts Meta
411 Sports
413 Sports Meta
415 Academia
417 Academia Meta
419 Computer Science
421 Computer Science Meta
423 The Workplace
425 The Workplace Meta
427 Windows Phone
429 Windows Phone Meta
431 Chemistry
433 Chemistry Meta
435 Chess
437 Chess Meta
447 Raspberry Pi
449 Raspberry Pi Meta
451 Russian Language
453 Russian Language Meta
455 Islam
457 Islam Meta
459 Salesforce
461 Salesforce Meta
463 Ask Patents
465 Ask Patents Meta
467 Genealogy & Family History
468 Genealogy & Family History Meta
469 Robotics
470 Robotics Meta
471 ExpressionEngine® Answers
472 ExpressionEngine® Answers Meta
475 Politics
476 Politics Meta
477 Anime & Manga
478 Anime & Manga Meta
479 Magento
480 Magento Meta
481 English Language Learners
482 English Language Learners Meta
483 Sustainable Living
484 Sustainable Living Meta
485 Tridion
486 Tridion Meta
489 Reverse Engineering
490 Reverse Engineering Meta
496 Network Engineering
497 Network Engineering Meta
498 Open Data
499 Open Data Meta
500 Freelancing
501 Freelancing Meta
502 Blender
503 Blender Meta
504 MathOverflow
505 MathOverflow Meta
508 Space Exploration
509 Space Exploration Meta
512 Sound Design
513 Sound Design Meta
514 Astronomy
515 Astronomy Meta
516 Tor
517 Tor Meta
518 Pets
519 Pets Meta
520 Amateur Radio
521 Amateur Radio Meta
524 Italian Language
525 Italian Language Meta
526 Stack Overflow em Português
527 Stack Overflow em Português Meta
528 Aviation
529 Aviation Meta
530 Ebooks
531 Ebooks Meta
532 Beer, Wine & Spirits
533 Beer, Wine & Spirits Meta
536 Software Recommendations
537 Software Recommendations Meta
540 Arduino
541 Arduino Meta
542 CS50
543 CS50 Meta
546 Expatriates
547 Expatriates Meta
548 Mathematics Educators
549 Mathematics Educators Meta
552 Meta Stack Overflow
553 Earth Science
554 Earth Science Meta
555 Joomla
556 Joomla Meta
557 Data Science
558 Data Science Meta
559 Puzzling
560 Puzzling Meta
563 Craft CMS
564 Craft CMS Meta
565 Buddhism
566 Buddhism Meta
567 Hinduism
568 Hinduism Meta
571 Community Building
572 Community Building Meta
579 Worldbuilding
580 Worldbuilding Meta
581 スタック・オーバーフロー
582 スタック・オーバーフローMeta
583 Emacs
584 Emacs Meta
587 History of Science and Mathematics
588 History of Science and Mathematics Meta
591 Economics
592 Economics Meta
593 Lifehacks
594 Lifehacks Meta
595 Engineering
596 Engineering Meta
597 Coffee
598 Coffee Meta
599 Vi and Vim
600 Vi and Vim Meta
601 Music Fans
602 Music Fans Meta
603 Woodworking
604 Woodworking Meta
605 CiviCRM
606 CiviCRM Meta
607 Medical Sciences
608 Medical Sciences Meta
609 Stack Overflow на русском
610 Stack Overflow на русском Meta
613 Русский язык
614 Русский язык Meta
615 Mythology & Folklore
616 Mythology & Folklore Meta
617 Law
618 Law Meta
619 Open Source
620 Open Source Meta
621 elementary OS
622 elementary OS Meta
625 Portuguese Language
626 Portuguese Language Meta
633 Computer Graphics
634 Computer Graphics Meta
635 Hardware Recommendations
636 Hardware Recommendations Meta
637 Stack Overflow en español
638 Stack Overflow Meta en español
640 3D Printing
641 3D Printing Meta
642 Ethereum
643 Ethereum Meta
644 Latin Language
645 Latin Language Meta
646 Language Learning
647 Language Learning Meta
648 Retrocomputing
649 Retrocomputing Meta
650 Arts & Crafts
651 Arts & Crafts Meta
654 Korean Language
655 Korean Language Meta
656 Monero
657 Monero Meta
658 Artificial Intelligence
659 Artificial Intelligence Meta
662 Esperanto Language
663 Esperanto Language Meta
664 Sitecore
665 Sitecore Meta
666 Internet of Things
667 Internet of Things Meta
668 Literature
669 Literature Meta
670 Veganism & Vegetarianism
671 Veganism & Vegetarianism Meta
672 Ukrainian Language
673 Ukrainian Language Meta
674 DevOps
675 DevOps Meta
676 Bioinformatics
677 Bioinformatics Meta
678 Computer Science Educators
679 Computer Science Educators Meta
680 Interpersonal Skills
681 Interpersonal Skills Meta
684 Iota
685 Iota Meta
686 Stellar
687 Stellar Meta
692 Constructed Languages
693 Constructed Languages Meta
694 Quantum Computing
695 Quantum Computing Meta
696 EOS.IO
697 EOS.IO Meta
698 Tezos
699 Tezos Meta
700 Operations Research
701 Operations Research Meta
702 Drones and Model Aircraft
703 Drones and Model Aircraft Meta
704 Matter Modeling
705 Matter Modeling Meta
706 Cardano
707 Cardano Meta

There must be a better way....

You may obtain an updated list at any time by running the following in the console from any site, which will replace the current page with the output (so run it in a tab you aren't working in):

$.getJSON('/topbar/site-switcher/all-pinnable-sites', function (sites) {
    var s = '';
    for (let site of sites.sort((a,b) => a.siteid - b.siteid))
        s += `${('   ' + site.siteid).slice(-3)} ${site.sitename}\n`
    $('html').empty().append($('<body\>').append($('<pre\>').text(s)));
});
8
  • 10
    There is a better way! The site ID's are contained in the markup of the "More Stack Exchange Communities" area of the MultiCollider/site switcher.
    – Steven V
    Commented Sep 4, 2014 at 16:21
  • 2
    @StevenV do you know of a better way to get the Meta ID's as well? The only way I can find is to go to each main site and find the .related-site's site-id attribute... Commented Dec 26, 2016 at 19:57
  • 1
    @ᔕᖺᘎᕊ I poked around and couldn't find a central location of the Meta ID's. Crawling is probably what I would do... Sorry!
    – Steven V
    Commented Dec 27, 2016 at 15:39
  • @StevenV No problem! Thanks for looking into it though! :) Commented Dec 27, 2016 at 15:40
  • 1
    These are all listed directly at meta.stackexchange.com/topbar/site-switcher/all-pinnable-sites, including metas. Here's a prettified paste of the results as of this comment.
    – Jason C
    Commented Jun 4, 2017 at 1:48
  • I updated your post. Also there's a little code snippet you can run to get the latest list at any time. cc @StevenV
    – Jason C
    Commented Jun 4, 2017 at 2:20
  • The single source of truth for the site list is How can I get URLs and site names for a cross-site SEDE query?. Commented Dec 29, 2021 at 13:07
  • Since less than a day ago, it's no longer easy to get the list from https://meta.stackexchange.com/topbar/site-switcher/all-pinnable-sites programatically. I get some HTML with an "enable Javascript" message instead of the JSON document. Of course it still loads fine in a browser. For now, I've solved this by copying the JSON file into my app as a file, and that's okay-ish since it doesn't change often. But it's not a great solution.
    – Jorn
    Commented Sep 22, 2023 at 7:22
20

I'm working on putting the communication with the Stack Exchange websockets inside a .NET library so as a way of sharing the research, here are the layouts of the JSON responses.

Note that they don't always work on all sites. For example 1 (Stack Overflow) does not respond to questions-active but 155 (all sites) does.

Last note: the data field is always in a string representation as has been noted above. Don't forget to pull it through your JSON parser again (in the samples below I replaced \" with " so it would be more readable).

155-questions-active

{
    "action" : "155-questions-active",
    "data" : "{
        "siteBaseHostAddress" : "biology.stackexchange.com",
        "id" : 17647,
        "titleEncodedFancy" : "Meaning of “auto” in trans autophosphorylation?",
        "bodySummary" : "why this process called Auto? <body> ...",
        "tags" : ["cell-signaling"],
        "lastActivityDate" : 1401048843,
        "url" : "http://biology.stackexchange.com/questions/17647/meaning-of-auto-in-trans-autophosphorylation",
        "ownerUrl" : "http://biology.stackexchange.com/users/6524/n00b",
        "ownerDisplayName" : "N00B",
        "apiSiteParameter" : "biology\
    "}"
}

<siteId>-questions-active

<siteId>-questions-newest

<siteId>-questions-newest-tag-<tag>

Note that tag has to be lowercase to work. This response is very ugly: it is littered with HTML inside the body field so the use of it is very limited. The response is the same for all three endpoints (although, once more, some sites like Stack Overflow only work with the latter of the three).

{
    "action" : "1-questions-newest-tag-java",
    "data" : "{
        "id" : "23859640",
        "body" : "<div class=\\"question-summary\\" id=\\"question-summary-23859640\\">\\r\\n <snipped a whole lot of html tags>",
        "tags" :  ["java","jfreechart"],
        "siteid" : 1,
        "fetch" : false
    }"
}

<siteId>-question-<questionId>

This one will return several different JSON's, depending on the activity that occurs at question in question.

I have not been able to observe all events yet but so far I believe no events are raised for these actions:

  • Closing the question
  • Deleting a comment
  • Editing a comment
  • Deleting an answer
  • Voting to close
  • Voting to delete (educated guess)
  • Upvoting a comment
  • Flagging (educated guess)

Post edit

{
    "action" : "1-question-23851409",
    "data" :"{
        "a" : "post-edit",
        "id" : 23851409,
        "acctid" : 2095246
    }"
}

Comment add

{
    "action" : "1-question-23851409",
    "data" : "{
        "a" : "comment-add",
        "id" : 23851409,
        "commentid" : 36706586,
        "acctid" : 4507832
    }"
}

Score change

Note: the score is the netto result score (so not just -1 and +1).

{
    "action" : "1-question-23851323",
    "data" : "{
        "a" : "score",
        "id" : 23851382,
        "score" : 1
    }"
}

Answer add

{
    "action" : "1-question-23851323",
    "data" : "{
        "a" : "answer-add",
        "id" : 23851323,
        "answerid" : 23851831,
        "acctid" : 1319955
    }"
}

Answer accept

{
    "action" : "1-question-23855163",
    "data" : "{
        "a" : "accept",
        "id" : 23855163,
        "answerid" : 23855182,
        "acctid" : 4520031
    }"
}

Answer unaccept

{
    "action" : "1-question-23855163",
    "data" : "{
        "a" : "unaccept",
        "id" : 23855163,
        "answerid" : 23855182,
        "acctid" : 4520031
    }"
}

<siteId>-review-dashboard-update

{
    "action" : "1-review-dashboard-update",
    "data" : "{
        "i" : 5,
        "u" : 3305005,
        "html" : "<a href=\\"/users/3305005/dr-jukka\\"> snipped tags"
    }"
}

Review types:

1 - Suggested edits
2 - Close votes
3 - Low Quality posts
4 - First posts
5 - Late answers
6 - Reopen
4
  • I observe an entirely different response for siteId-questions-active than for 155-questions-active (the realtime SE tab). Should I edit? Commented Jun 22, 2014 at 8:53
  • I haven't tested it with something different from 155. What siteId gives you a different response? Commented Jun 22, 2014 at 8:55
  • 1
    Tested on SuperUser, but I assume that every per-site socket does that. The response is pretty ugly IMO. Commented Jun 22, 2014 at 8:56
  • You're right, it does send a different response. Feel free to edit it in. It is indeed an ugly response; just like <siteId>-questions-newest-tag-<tag> it throws a lot of HTML inside the body. Commented Jun 22, 2014 at 9:01
14

The chat websockets automatically close, for some reason. Manish or I haven't figured this out yet. However, there is another way to retrieve chat messages. Here are the chat event_types I've found so far:

 1 | message posted
 2 | message edited
 3 | user joined
 4 | user left
 6 | message starred or unstarred
 8 | someone @-notified you (in any room)
10 | message deleted
18 | someone replied to one of your messages (in any room)
19 | message moved out of room
20 | message moved into room

You can get all events since a certain time by POSTing to this URL:

http://chat.stackexchange.com/events

With these parameters:

r{room number}={timestamp}&fkey={your fkey}

(It returns JSON.)

10
  • Have you figured out what the fkey is yet?
    – ɥʇǝS
    Commented Feb 3, 2014 at 18:05
  • @ɥʇǝS It's just the standard chat fkey.
    – Doorknob
    Commented Feb 4, 2014 at 2:32
  • 5
    If it's of any use - I managed to get this off @balpha a while back: gist.github.com/joncle/9198621 Commented Feb 24, 2014 at 22:29
  • @JonClements great, thanks. Even better - can you get off him a feed of all active answers across the network? Commented Feb 25, 2014 at 14:22
  • 1
    The websockets apparently need a valid Origin: header. The python websocket client seems to send the header twice :/ Commented Feb 25, 2014 at 16:58
  • ...and I have the latest update to the list: paste.ubuntu.com/12785810 Commented Oct 15, 2015 at 3:22
  • Apparently you have to respond to heartbeat messages to keep the connection alive. codegolf.stackexchange.com/questions/150318/… Commented Dec 14, 2017 at 1:48
  • @Carcigenicate Do you have more details on that? Do you know what do the heartbeat messages look like, or what response is expected? Thanks!
    – rydwolf
    Commented May 29, 2021 at 17:28
  • 1
    @RedwolfPrograms I posted that 3 years ago. From my code that I linked to though, I was just sending "hb". The "question" that I answered there has information Commented May 29, 2021 at 17:31
  • @Carcigenicate Didn't notice the question included that, thanks!
    – rydwolf
    Commented May 29, 2021 at 17:34
7

Too long for a comment, but not really an answer.

If you do:

curl -L https://chat.stackexchange.com/rooms/1

you will see something like this in the result:

<input id="fkey" name="fkey" type="hidden" value="[hex digits]" />;

The [hex digits] are your fkey. Now, you can do something like:

curl -d 'fkey=[hex digits]&r36=0&r49=0&r24938=0' https://chat.stackexchange.com/events

to see the latest messages in rooms 36, 49, and 24938.

You can get rooms numbers from https://chat.stackexchange.com/ by looking at the links. For example, the current link to "Normal Chatroom" is https://chat.stackexchange.com/rooms/30985/normal-chatroom so the room id is 30985.

The result of the curl command above is in JSON and looks somethng like this:

{"event_type":1,"time_stamp":1449953439,"content":"Anyone here know much about stats?","id":49015167,"user_id":76516,"user_name":"Anthony","room_id":36,"room_name":"Mathematics","message_id":26121166}

The 'id' field above (49015167 in this case) is a universal id that increments across all chats, and you can use it to limit your results as follows:

curl -d 'fkey=[hex digits]&r36=49015167&r49=49015167&r24938=49015167' https://chat.stackexchange.com/events

The above will show you messages after (and including) message 49015167.

Note that the id field isn't really a timestamp, and shouldn't be confused with the fields time_stamp or message_id.

I'm doing something like this at: https://github.com/barrycarter/bcapps/blob/master/STACK/bc-stalk-chats.pl

I suspect something like ncat might work better than curl, but this is what I have so far.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .