首页 > 解决方案 > 运行代码时出现错误“SyntaxError: invalid syntax”

问题描述

我尝试在我的树莓派 3 上运行此代码,但我遇到了这个问题

我试图卸载电报库,但他说 E: Unable to locate package telegram

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
  File "/usr/local/lib/python2.7/dist-packages/python_telegram_bot-12.0.0b1-py2.7.egg/telegram/ext/__init__.py", line 28, in <module>
    from .updater import Updater
  File "/usr/local/lib/python2.7/dist-packages/python_telegram_bot-12.0.0b1-py2.7.egg/telegram/ext/updater.py", line 33, in <module>
    from telegram.utils.webhookhandler import (WebhookServer, WebhookAppClass)
  File "/usr/local/lib/python2.7/dist-packages/python_telegram_bot-12.0.0b1-py2.7.egg/telegram/utils/webhookhandler.py", line 27, in <module>
    from tornado.httpserver import HTTPServer
  File "/usr/local/lib/python2.7/dist-packages/tornado-6.0.2-py2.7-linux-armv7l.egg/tornado/httpserver.py", line 144
    def __init__(self, *args: Any, **kwargs: Any) -> None:
                            ^
SyntaxError: invalid syntax

我试图卸载电报库,但他说 E: Unable to locate package telegram

https://github.com/python-telegram-bot/python-telegram-bot/issues/395

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
import time
import RPi.GPIO as GPIO
import Adafruit_DHT
led = 5
DHT_pin = 27

GPIO.setmode(GPIO.BOARD)
GPIO.setup(led, GPIO.OUT, initial = 0)
# Enable logging
#logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
 #                   level=logging.INFO)

#logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def on(bot, update):
    """Send a message when the command /start is issued."""
    GPIO.output(led, GPIO.HIGH)
    update.message.reply_text('LED turned ON')

def off(bot, update):
    """Send a message when the command /help is issued."""
    GPIO.output(led, GPIO.LOW)
    update.message.reply_text('LED turned OFF')

def hum(bot, update):
    """Send a message when the command /hum is issued."""
    humidity = Adafruit_DHT.read_retry(11, DHT_pin)[0]
    update.message.reply_text("Humidity: {} %".format(humidity))

def temp(bot, update):
    """Send a message when the command /temp is issued."""
    temperature = Adafruit_DHT.read_retry(11, DHT_pin)[1]
    update.message.reply_text("Temperature: {} C".format(temperature))

def echo(bot, update):
    """Echo the user message."""
    update.message.reply_text(update.message.text)

def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)

def main():
    """Start the bot."""
    # Create the EventHandler and pass it your bot's token.
    updater = Updater("Enter your token here")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("on", on))
    dp.add_handler(CommandHandler("off", off))
    dp.add_handler(CommandHandler("temp", temp))
    dp.add_handler(CommandHandler("hum", hum))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()

标签: pythonraspberry-pitelegram-bot

解决方案


也许您正在尝试使用 Python2 运行代码?语法错误抱怨库代码中使用的类型注释。这些输入提示是在 Python3.5 中引入的。


推荐阅读