斗鱼向第三方开放了弹幕API,网上已经有很多用Python、Java等流行开发语言写的弹幕程序,今天我拿斗鱼弹幕来抛砖引玉,有不正之处,还请大家批评指正,多多评论哈!
准备工作:
1.PowerShell
2.斗鱼弹幕API协议,http://dev-bbs.douyutv.com/forum.php?mod=viewthread&tid=399&extra=page=1
代码如下:
#斗鱼弹幕服务器地址、端口
$douyu_server="openbarrage.douyutv.com"
$douyu_port=8601
#要查看的房间号,xxxxx改成房间的id号
$roomid=xxxxx
$socket = new-object System.Net.Sockets.TcpClient($douyu_server, $douyu_port)
$send = new-object System.Byte[] 1024
$recv = new-object System.Byte[] 1024
$end_byte = new-object System.Byte
$encode = new-object System.Text.UTF8Encoding
$stream = $socket.GetStream()
function Sendmsg($msg)
{
#把字符串转换为byte数组
$msg_byte = $encode.GetBytes($msg)
#调用BitConverter的GetBytes方法把值转换为byte数组
$len_byte = [System.BitConverter]::GetBytes(4 4 $msg_byte.length 1)
$magic_byte = [System.BitConverter]::GetBytes(0x2b1)
$end_byte = 0x0
$send = $len_byte $len_byte $magic_byte $msg_byte $end_byte
$stream.Write($send, 0, $send.Length)
}
#参照斗鱼API写请求
$login="type@=loginreq/roomid@=$roomid/"
$joingroup="type@=joingroup/rid@=$roomid/gid@=-9999/"
#发送请求
SendMsg($login)
SendMsg($joingroup)
#接收弹幕
while(1)
{
$recvi=$stream.Read($recv,0,$recv.Length)
if($recv.Length -ne 0)
{
$str=$encode.GetString($recv,0,$recvi)
#正则表达式,用了子表达式取出等号右边的值
$regex = [regex]"type@=([\W\w][^@=/]*)/"
$type = $regex.Matches($str)
if($type[0].Groups[1].Value -eq "chatmsg")
{
$regex1 = [regex]"nn@=([\W\w][^@=/]*)/"
$regex2 = [regex]"txt@=([\W\w][^@=/]*)/"
$name = $regex1.Matches($str)
$danmu = $regex2.Matches($str)
write-host($name[0].Groups[1].Value ":" $danmu[0].Groups[1].Value)
}
}
}
$socket.Close()
弹幕效果
这个程序还是很粗糙的,像心跳响应等都没有实现,只是给大家一个演示,说明PowerShell的功能不比其它编程语言差,好了,今天就到这吧,感谢大家对我的支持与鼓励。