Last active
December 18, 2015 16:49
-
-
Save meritt/5814557 to your computer and use it in GitHub Desktop.
Twitter Streaming API v1.1 + node.js + socket.io
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
twitter = require 'twitter-text' | |
module.exports = (tweet) -> | |
# Преобразуем только ссылки, хештеги и аккаунты оставляем текстом | |
text = twitter.autoLinkUrlsCustom tweet.text, target: '_blank' | |
# Заменяем сжатые ссылки на нормальные | |
if tweet.entities.urls? and tweet.entities.urls.length > 0 | |
for entity in tweet.entities.urls | |
text = text.replace entity.url, entity.expanded_url | |
text = text.replace entity.url, entity.display_url | |
# Заменяем ссылки на картинки на сами изображения | |
tweet.media = false | |
if tweet.entities.media? and tweet.entities.media.length > 0 | |
for entity in tweet.entities.media | |
text = text.replace entity.url, entity.expanded_url | |
text = text.replace entity.url, entity.display_url | |
tweet.media = | |
url: entity.media_url | |
w: entity.sizes.small.w | |
h: entity.sizes.small.h | |
tweet.text = text | |
# Заменяем размеры аватаров на максимальные | |
image = tweet.user.profile_image_url | |
pos = image.lastIndexOf '_' | |
tweet.user.profile_image_url = image.substring(0, pos) + '_bigger' + image.substring(pos + 7) | |
tweet |
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
(function(window, document) { | |
'use strict'; | |
var socket = window.io.connect('http://127.0.0.1:8080'), | |
// Получаем шаблон | |
template = document.getElementById('twitter-template').innerHTML, | |
// Контейнер со всеми сообщениями | |
container = document.getElementById('twitter-feed'), | |
messages = []; | |
// Все новые сообщения добавляем в массив messages | |
socket.on('connect', function() { | |
socket.on('message', function(result) { | |
messages.push(JSON.parse(result)); | |
}); | |
}); | |
// Каждые 2 секунды берём первое сообщение из массива и показываем | |
window.setInterval(function() { | |
if (messages.length > 0) { | |
var message = messages.shift(), | |
// Получаем все сообщения в ленте | |
tweets = container.querySelectorAll('section'), | |
length = tweets.length, | |
section = document.createElement('section'); | |
// Создаём HTML шаблон для нового сообщения | |
section.innerHTML = mustache(template, message); | |
if (length > 0) { | |
container.insertBefore(section, tweets[0]); | |
} else { | |
container.appendChild(section); | |
} | |
// Если в ленте больше 20 сообщений, удаляем самое старое | |
if (length > 20) { | |
container.removeChild(tweets[length-1]); | |
} | |
} | |
}, 2000); | |
})(window, document); |
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
http = require 'request' | |
module.exports = (track, oauth, fn) -> | |
params = | |
url: 'https://stream.twitter.com/1.1/statuses/filter.json' | |
oauth: oauth | |
form: | |
include_entities: true | |
track: track | |
request = http.post params, (error) -> | |
fn error, false if error | |
request.on 'data', (buffer) -> | |
try | |
tweet = JSON.parse buffer.toString() | |
catch error | |
tweet = false | |
if tweet | |
data = | |
id: tweet.id_str | |
link: "http://twitter.com/#{tweet.user.screen_name}" | |
avatar: tweet.user.profile_image_url | |
login: tweet.user.screen_name | |
name: tweet.user.name or tweet.user.screen_name | |
text: tweet.text | |
fn null, data |
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
clients = [] | |
io = require('socket.io').listen(8080) | |
io.sockets.on 'connection', (socket) -> | |
clients.push socket | |
oauth = | |
consumer_key: 'consumer key' | |
consumer_secret: 'consumer secret' | |
token: 'oauth token' | |
token_secret: 'token secret' | |
send = (tweet) -> | |
client.send JSON.stringify tweet for client in clients | |
filter = require './twitter/filter' | |
filter 'html5,css3', oauth, (error, tweet) -> | |
send tweet unless error |
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
oauth = | |
consumer_key: 'consumer key' | |
consumer_secret: 'consumer secret' | |
token: 'oauth token' | |
token_secret: 'token secret' | |
filter = require './twitter/filter' | |
filter 'html5,css3', oauth, (error, tweet) -> | |
console.log tweet unless error |
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
twitter = require 'twitter-text' | |
options = | |
# список нежелательных аккаунтов (для тролей) | |
mute: [''] | |
# список стоп-слов (для спама) | |
spam: ['купить javascript без смс'] | |
module.exports = (tweet) -> | |
return false if not tweet or not tweet.user or not tweet.text | |
# Разрешены сообщения только на русском и английском | |
if tweet.lang? | |
return false if tweet.lang not in ['en', 'ru'] | |
else if tweet.user.lang? | |
return false if tweet.user.lang not in ['en', 'ru'] | |
# Пропускаем нежелательные аккаунты | |
if options.mute.length > 0 | |
account = "#{tweet.user.screen_name}".toLowerCase() | |
return false for mute in options.mute when account is mute | |
# Пропускаем пользователей с аватаром по-умолчанию ^_^ | |
if tweet.user.profile_image_url.indexOf('default_profile_images') > -1 | |
return false | |
text = "#{tweet.text}" | |
# Пропускаем старые ретвиты и ответы на сообщения | |
if text.indexOf('RT ') is 0 or text.indexOf('@') is 0 or text.indexOf('.@') is 0 | |
return false | |
if options.spam.length > 0 | |
# Преобразуем сжатые ссылки в полный вид | |
if tweet.entities.urls? and tweet.entities.urls.length > 0 | |
for entity in tweet.entities.urls | |
text = text.replace entity.url, entity.expanded_url | |
text = text.toLowerCase() | |
# Пропускаем твиты содержащие в себе стоп-слова | |
return false for spam in options.spam when text.indexOf(spam) isnt -1 | |
# Пропускаем твиты содержащие переизбыток хештегов ^_^ | |
hashtags = twitter.extractHashtagsWithIndices text | |
return false if hashtags and hashtags.length > 4 | |
return true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Примеры кода для статьи «Пульс твиттера о веб-разработке».
http://simonenko.su/53381781858/pulse-of-web-developments