我想问一下,如何在Python中将以下内容编写为模块。
if message.content.startswith('!guess'):
# Game Status updating
now_playing = discord.Game(name='Guessing Game')
await self.change_status(game=now_playing, idle=False)
await self.send_message(message.channel, 'Guess a number between 1 to 10')
def guess_check(m1):
return m1.content.isdigit()
guess = await self.wait_for_message(timeout=5.0, author=message.author, check=guess_check)
answer = random.randint(1, 10)
if guess is None:
fmt = 'Sorry, you took too long. It was {}.'
await self.send_message(message.channel, fmt.format(answer))
return
if int(guess.content) == answer:
await self.send_message(message.channel, 'You are right!')
else:
await self.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))
# Game Status updating
now_playing = discord.Game(name='')
await self.change_status(game=now_playing, idle=False)
因此我可以使用说guessgame.guess()
答案 0 :(得分:5)
创建一个名为guessgame.py
的Python模块文件,然后在其中定义:
"""
This is the module guessgame, it lives in the file guessgame.py
Put some documentation about your module here
"""
def guess(message):
# Put your code here
然后从另一个模块,例如您可以执行sample.py
(或Python / IPython shell会话):
import guessgame
guessgame.guess(message='something') # What you wanted
运行时警告:从未等到过'猜测'猜测.gigg()
# 'await' can only be used inside a coroutine
# if you want guess to be a coroutine, define it like below
async def guess(message):
# Put your code that uses await
# Now you can use await expressions
await
,需要额外注意,请详细了解这些内容:https://www.python.org/dev/peps/pep-0492/#examples-of-await-expressions guess
名称,因为您的功能已被称为guessname.guess()
,如果您重新定义{> 它 {1}} guess
已通过所有必需参数,仅用于说明目的我只包含一个参数guess = ...
guessgame.guess()
,这表明这应该是一个类的方法而不是一个独立的函数?请记住一些事情!