Total Pageviews

Friday 4 January 2019

通过Telegram Bot 把语音信息发送到 Raspberry Pi并播放

  • 想到了利用树莓派来播放语音, 树莓派插上广播, 使用mplayer播放语音文件, 可以达到这个目的.
    现在经常用来把下班行程告诉岳母, 然后根据语音提示,合理的安排做饭时间. 一般到家正好开饭. 哈哈。

    硬件

    • 树莓派 2 代Model B (1/3代也肯定没问题, 我只有一个2代.)
    • 广播(淘宝10~20元即可, usb供电)

    软件

    • 树莓派需要公网IP, 或者内网穿透需要有公网的服务器(推荐frp, 真是稳如狗, 我现在就是使用的它)
    • 注册telegram, 创建telegram bot. (telegram已经被屏蔽, 需要翻墙自行解决), 
      之前也想通过微信公众号来做, 奈何微信公众号需要认证(费用300/年)个人公众号还无法认证, QTMD微信, 我就想接收一个语言文件而已.

    Telegram Bot

    我也由此接触到Telegram, 知道到了telegram bot可以做很多事件, 
    深入了解后我也加入了有很多开车群(哎, 不说了, 你懂的, 赶紧喝袋牛奶补补, 要不然营养跟不上了, 哈哈).
    • 注册Telegram就不多说了, 有手机号的都行(google voice也可以)
    • 创建Telegram bot https://core.telegram.org/bots 这是telegram bot地址, 跟着步骤你就可以创建你想实现的bot.
    这里我简单说几点:
    BotFather 对话来创建bot. 
    创建完成你应该得到一个bot token, 类似这个317386679:AAGvecIfPbxZpPtlT4iNOKkIcufgRNk19JM.
  • Bot 接收消息有两种互斥的方法, 一个getUpdates主动去请求服务查看是否有新消息,
    另一个是Webhooks, 当服务有新消息,会主动把消息转给你设定好的API地址, 这些方式需要占用一个443端口, 
    这两种方式看个人喜好, 我个人推荐第二种, 不占用443端口, 详细看这里https://core.telegram.org/bots/api
  • 由于Telegram bot api 比较成熟, 已经有许多语言的SDK直接拿过来就可以使用, 写自己的逻辑代码就行了, 
    我刚开始使用是.Net版本https://github.com/TelegramBots/telegram.bot
    后来又换成了Python版本https://github.com/python-telegram-bot/python-telegram-bot

Telegram Bot 接收消息

消息包括命令, 语音, 文本, 图片, 音频, 视频等
我们做的主要是处理语音, 把收到的语音添加到一个消息队列, 后台再慢慢把语音文件发送到树莓派指定文件夹.
  • 处理语音, 并下载语音文件(Bot有一个限制, 接收文件最大不超过20MB)
def audio_process(bot, update):
    audio = update.message.audio if update.message.audio else update.message.voice
    file = bot.get_file(audio.file_id)

    filename = '{}-{}.{}'.format(datetime.today().strftime('%Y%m%d-%H%M%S'), audio.file_id, file.file_path.split('.')[-1])
    filepath = '{}/{}'.format(common.voice_path, filename)
    #print(filepath, file.file_path)
    with open(filepath, 'wb') as f:
        file.download(out = f)

    #sync file
    sync_file.enter(filename)

    bot.send_message(chat_id= update.message.chat_id, text = 'Thanks, we have received your voice...')
  • 然后把语音文件发送树莓派指定文件夹
    def sync_file(self, filename):
        logging.info('start sync file:{}'.format(filename))

        localFile = '{}/{}'.format(common.voice_path, filename)
        remoteFile = '{}/{}'.format(common.ssh_path, filename)

        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        client.connect(common.ssh_server, common.ssh_port, common.ssh_username, common.ssh_password)

        sftp = client.open_sftp()
        sftp.put(localFile, remoteFile)
        sftp.close()
        client.close()

        logging.info('end sync file:{}'.format(filename))
  • 树莓派每分钟都会执行脚本检查是否有新的语音文件, 如果有新的语音文件就播放, 并把它移动到Backup文件夹.
#!/bin/bash

path=~/tmp/*
backup=~/tmp/backup
player=/usr/bin/mplayer
reminder=~/tmp/remind/reminder.mp3
flag=true

for file in $path
do
        if [ -f $file ];then
                #echo $file
                if [ "$flag" ] ; then
                        $player $reminder
                        flag=false
                fi
                $player $file
                $player $file
                mv $file $backup
        fi
done

总结

代码是不是很简单, 完整项目在Github上 https://github.com/tianzhenyun/python-telegram-bot
这里有详细的代码, 有需要的同学可以仔细看一下.
--------------------

用Raspberry Pi整点报时

完整的音频文件及脚本: Github
参考链接:
  • 安装Mplayer
  • 下载语音文件(解压到/{home})
  • 创建脚本文件TimeAudio.sh(/usr/local/bin)
#!/bin/bash

filePath=/{home}/TimeAudio
Time=`date +%H%M`
audioFile="$filePath/$Time.mp3"
#echo $audioFile
player=/usr/bin/mplayer

$player $audioFile
  • 保存后加执行权限:
chmod +x /usr/local/bin/TimeAudio.sh
  • 加入定时计划 crontab, 运行:crontab -e 添加如下代码
0 * * * * /usr/local/bin/TimeAudio.sh

No comments:

Post a Comment