def progress(self, msg: discord.Message, begin_txt: str):
"""Play loading animation with dots and moon."""
fmt = '{0}{1} {2}'
anim = '????????????????????'
anim_len = len(anim) - 1
anim_i = 0
dot_i = 1
while True:
await msg.edit(content=fmt.format(begin_txt, ('.' * dot_i) + ' ' * (3 - dot_i), anim[anim_i]))
dot_i += 1
if dot_i > 3:
dot_i = 1
anim_i += 1
if anim_i > anim_len:
anim_i = 0
await asyncio.sleep(1.1)
python类Message()的实例源码
def do_stop(self, message: Message, member: Member):
if member.id != "90269810016923648":
await self.bot.send_message(message.channel, "Only the Owner can use this command")
return
state = self.get_voice_state(message.server)
if state.is_playing():
player = state.player
player.stop()
await self.bot.send_message(message.channel, "Stopping...")
try:
state.audio_player.cancel()
del self.voice_states[message.server.id]
await state.voice.disconnect()
await self.bot.send_message(message.channel, "Ok bye...")
except:
pass
def do_skip(self, message: Message, voter: Member):
state = self.get_voice_state(message.server)
if not state.is_playing():
await self.bot.send_message(message.channel, "Not playing any music right now...")
return
if voter == state.current.requester:
await self.bot.send_message(message.channel, "Requester requested skipping song...")
state.skip()
elif voter.id not in state.skip_votes:
state.skip_votes.add(voter.id)
total_votes = len(state.skip_votes)
if total_votes >= 3:
await self.bot.send_message(message.channel, "Skip vote passed, skipping song...")
state.skip()
else:
await self.bot.send_message(message.channel, "Skip vote added, currently at [{}/3]".format(total_votes))
else:
await self.bot.send_message(message.channel, "You have already voted to skip this song.")
def safe_send_message(self, dest, content, *, tts=False, expire_in=0, also_delete=None, quiet=False):
msg = None
try:
msg = await self.send_message(dest, content, tts=tts)
if msg and expire_in:
asyncio.ensure_future(self._wait_delete_msg(msg, expire_in))
if also_delete and isinstance(also_delete, discord.Message):
asyncio.ensure_future(self._wait_delete_msg(also_delete, expire_in))
except discord.Forbidden:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, no permission" % dest.name)
except discord.NotFound:
if not quiet:
self.safe_print("Warning: Cannot send message to %s, invalid channel?" % dest.name)
return msg
def remove_all(self, message: discord.Message, config: dict=None):
"""Remove all stars from a message.
Parameters
----------
message: `discord.Message`
Message that is going to have all stars removed.
"""
lock = self._locks[message.guild.id]
await lock
try:
if not config:
config = await self._get_starconfig(message.guild.id)
star = await self.raw_remove_all(config, message)
await self.update_star(config, star, delete=True)
finally:
lock.release()
def star(self, ctx, message_id: int):
"""Star a message."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
try:
await self.add_star(message, ctx.author)
await ctx.ok()
except (StarAddError, StarError) as err:
log.warning(f'[star_command] Errored: {err!r}')
return await ctx.send(f'Failed to add star: {err!r}')
def unstar(self, ctx, message_id: int):
"""Unstar a message."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
try:
await self.remove_star(message, ctx.author)
await ctx.ok()
except (StarRemoveError, StarError) as err:
log.warning(f'[unstar_cmd] Errored: {err!r}')
return await ctx.send(f'Failed to remove star: {err!r}')
def starrers(self, ctx, message_id: int):
"""Get the list of starrers from a message in the current channel."""
try:
message = await ctx.channel.get_message(message_id)
except discord.NotFound:
return await ctx.send('Message not found')
except discord.Forbidden:
return await ctx.send("Can't retrieve message")
except discord.HTTPException as err:
return await ctx.send(f'Failed to retrieve message: {err!r}')
guild = ctx.guild
await self._get_starconfig(guild.id)
star = await self.get_star(guild.id, message.id)
if star is None:
return await ctx.send('Star object not found')
_, em = make_star_embed(star, message)
starrers = [guild.get_member(starrer_id)
for starrer_id in star['starrers']]
em.add_field(name='Starrers', value=', '.join([m.display_name
for m in starrers]))
await ctx.send(embed=em)
def download_data(self, message: discord.Message) -> str:
"""Checks if an attachment is viable to be used as
MIDI input and downloads it."""
if not message.attachments:
raise self.SayException('You did not attach a file to '
'use as MIDI input!, `j!help midi`')
attachment = message.attachments[0]
if not attachment.filename.endswith('.txt'):
raise self.SayException('File must be a .txt!')
# see if the file is bigger than 20 KiB as we don't want
# to download huge files
if attachment.size >= 20 * 1024:
raise self.SayException('File is too large. '
'Your file may only be 20KiB big.')
log.info('downloading file to use as MIDI input. '
f'{attachment.size} bytes large.')
buffer = io.BytesIO()
await attachment.save(buffer)
return buffer.getvalue().decode('utf-8')
def on_message_delete(message):
"""
Event handler, fires when a message is deleted
:param message: discord.Message object containing the deleted message
"""
try:
if message.author.name != "PluginBot":
await pm.handle_message_delete(message)
except Exception as e:
await client.send_message(message.channel, "Error: " + str(e))
if pm.botPreferences.get_config_value("client", "debug") == "1":
traceback.print_exc()
def on_error(event_method, *args, **kwargs):
type, value, _traceback = sys.exc_info()
if type is discord.errors.Forbidden:
for arg in args:
if isinstance(arg, commands.context.Context):
print("Missing Permissions for #{0.channel.name} in {0.server.name}".format(arg.message))
return
elif isinstance(arg, discord.Message):
print("Missing Permissions for #{0.channel.name} in {0.server.name}".format(arg))
return
print('Ignoring exception in {}'.format(event_method), file = sys.stderr)
traceback.print_exc()
logging.errors_logger.error("Uncaught exception\n", exc_info = (type, value, _traceback))
def get_message(self, message):
"""Retrieves a Message from the database.
Parameters
----------
message
Can be a Message object or a message ID."""
if isinstance(message, discord.Message):
return Message.objects.get(id=message.id)
else:
return Message.objects.get(id=message)
def new_message(self, message):
"""Creates a new Dwarf ?Message? object and connects it to the database.
Parameters
----------
message
Has to be a Discord ?Message? object.
"""
if isinstance(message, discord.Message):
return Message(id=message.id, author=message.author.id, channel=message.channel,
content=message.content, clean_content=message.clean_content,)
else:
raise ValueError("A Message object must be given as an argument")
def answer_to_boolean(answer):
if isinstance(answer, discord.Message):
answer = answer.content
answer_lower = answer.lower()
if answer_lower.startswith('y'):
return True
if answer_lower.startswith('n'):
return False
return None
def is_boolean_answer(message):
if isinstance(message, discord.Message):
message = message.content
message_lower = message.lower()
return message_lower.startswith('y') or content_lower.startswith('n')
def is_expired(message):
"""Determines if a raid is expired, given its announcement message.
Message accepts the result returned by get_announcement_message (a valid obj or None).
:param message discord.Message: The announcement message associated with the raid.
:returns: True if the message/raid timestamp is expired
"""
if message is None:
return True # can't find message, clean up the raid channel
return (datetime.utcnow() - message.timestamp) > timedelta(seconds=settings.raid_duration_seconds)
def on_message(self, msg: discord.Message):
"""
Records the message and sender in the database. Also
increments the users total messages.
:param msg: the message
"""
if not msg.channel.is_private:
try:
# append embeds list to message
body = msg.content
if msg.embeds:
body += '\n' + str(msg.embeds)
user = self.orm.User.get_or_create(
discord_id=msg.author.id
)[0]
# Make sure to update the user so all relevant info is there
update_user_fields(user, msg.author)
server = self.orm.Server.get_or_create(
discord_id=msg.channel.server.id
)[0]
channel = self.orm.Channel.get_or_create(
discord_id=msg.channel.id,
server=server
)[0]
self.orm.Message.create(
discord_id=msg.id,
user=user,
channel=channel,
body=body,
is_command=is_command(self.bot, msg.content),
is_embed=True if msg.embeds else False
)
except OperationalError as e:
self.config.logger.error(e)
def is_triggered_message(self, msg: discord.Message) -> bool:
"""
Is it triggered by a message, public or private?
@param msg: the message
:return: is it triggered?
"""
return False
def is_triggered_private_message(self, msg: discord.Message) -> bool:
"""
Is it triggered by a private message and ONLY a private message?
:param msg: the message
:return: is it triggered?
"""
return False
def on_message(self, msg: discord.Message):
"""
When triggered by a message, public or private
:param msg: the message
"""
pass