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
我知道我必须首先实例化类,但是在导入另一个模块时该怎么做。有人,请解释一下!
答案 0 :(得分:1)
您将必须首先实例化该类。
即。
from bot import T_bot
update_id = None
def make_reply(msg):
reply = 'okay'
return reply
update_id = None
instantiated_class = T_bot()
while True:
updates = instantiated_class.gett(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)