【发布时间】:2020-07-21 16:55:08
【问题描述】:
import requests
import json
token= "12882xxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
class T_bot:
def __init__(self):
self.base= "https://api.telegram.org/bot{}/".format(token)
self.sendurl= "https://api.telegram.org/bot{}/sendMessage".format(token)
#self.data= {'chat_id':1067109380, 'text': 'Hi I hope you are doing fine' }
def gett(self, offset=None):
url= self.base+"getUpdates?timeout=100"
if offset:
url = url+"&offset={}".format(offset+1)
a= requests.get(url)
return a.json()
def send(self, msg, chat_id):
url= self.base+"sendMessage?chat_id={}&text={}".format(chat_id,msg)
if msg is not None:
requests.get(url)
当我将上述代码 (bot.py) 导入为:
from bot import T_bot
update_id= None
def make_reply(msg):
reply= 'okay'
return reply
update_id= None
while True:
updates= T_bot.gett(self, offset= update_id)
updates= updates["result"]
if updates:
for item in updates:
update_id= item['update_id']
try:
message= item['message']['text']
except:
message= None
fromm= item['message']['from']['id']
reply= make_reply(message)
T_bot.send(reply, fromm)
当我运行上面的主文件时,它会抛出一个 NameError:
Traceback (most recent call last):
File "C:\Users\shivam\Desktop\pypy\server.py", line 13, in <module>
updates= T_bot.gett(self, offset= update_id)
NameError: name 'self' is not defined
我知道我必须先实例化类,但是当我导入另一个模块时我该怎么做。有人,请解释一下!
【问题讨论】:
-
T_bot.gett(self, offset= update_id)这不是类的使用方式。
标签: python-3.x