Browse Source

Update examples to match the new rewrite API.

pull/447/head
Rapptz 8 years ago
parent
commit
f8a5d890fe
  1. 37
      examples/background_task.py
  2. 30
      examples/basic_bot.py
  3. 29
      examples/deleted.py
  4. 30
      examples/edits.py
  5. 53
      examples/guessing_game.py
  6. 27
      examples/new_member.py
  7. 29
      examples/reply.py

37
examples/background_task.py

@ -1,23 +1,28 @@
import discord
import asyncio
client = discord.Client()
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
# create the background task and run it in the background
self.bg_task = self.loop.create_task(self.my_background_task())
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
client.loop.create_task(my_background_task())
async def my_background_task(self):
await self.wait_until_ready()
counter = 0
channel = self.get_channel(1234567) # channel ID goes here
while not self.is_closed:
counter += 1
await channel.send(counter)
await asyncio.sleep(60) # task runs every 60 seconds
client = MyClient()
client.run('token')

30
examples/basic_bot.py

@ -16,50 +16,50 @@ async def on_ready():
print('------')
@bot.command()
async def add(left : int, right : int):
async def add(ctx, left: int, right: int):
"""Adds two numbers together."""
await bot.say(left + right)
await ctx.send(left + right)
@bot.command()
async def roll(dice : str):
async def roll(ctx, dice: str):
"""Rolls a dice in NdN format."""
try:
rolls, limit = map(int, dice.split('d'))
except Exception:
await bot.say('Format has to be in NdN!')
await ctx.send('Format has to be in NdN!')
return
result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
await bot.say(result)
await ctx.send(result)
@bot.command(description='For when you wanna settle the score some other way')
async def choose(*choices : str):
async def choose(ctx, *choices: str):
"""Chooses between multiple choices."""
await bot.say(random.choice(choices))
await ctx.send(random.choice(choices))
@bot.command()
async def repeat(times : int, content='repeating...'):
async def repeat(ctx, times: int, content='repeating...'):
"""Repeats a message multiple times."""
for i in range(times):
await bot.say(content)
await ctx.send(content)
@bot.command()
async def joined(member : discord.Member):
async def joined(ctx, member: discord.Member):
"""Says when a member joined."""
await bot.say('{0.name} joined in {0.joined_at}'.format(member))
await ctx.send('{0.name} joined in {0.joined_at}'.format(member))
@bot.group(pass_context=True)
@bot.group()
async def cool(ctx):
"""Says if a user is cool.
In reality this just checks if a subcommand is being invoked.
"""
if ctx.invoked_subcommand is None:
await bot.say('No, {0.subcommand_passed} is not cool'.format(ctx))
await ctx.send('No, {0.subcommand_passed} is not cool'.format(ctx))
@cool.command(name='bot')
async def _bot():
async def _bot(ctx):
"""Is the bot cool?"""
await bot.say('Yes, the bot is cool.')
await ctx.send('Yes, the bot is cool.')
bot.run('token')

29
examples/deleted.py

@ -1,22 +1,21 @@
import discord
client = discord.Client()
class MyClient(discord.Client):
async def on_ready(self):
print('Connected!')
print('Username: {0.name}\nID: {0.id}'.format(self.user))
@client.event
async def on_ready():
print('Connected!')
print('Username: ' + client.user.name)
print('ID: ' + client.user.id)
async def on_message(self, message):
if message.content.startswith('!deleteme'):
msg = await message.channel.send('I will delete myself now...')
await msg.delete()
@client.event
async def on_message(message):
if message.content.startswith('!deleteme'):
msg = await client.send_message(message.channel, 'I will delete myself now...')
await client.delete_message(msg)
# this also works
await message.channel.send('Goodbye in 3 seconds...', delete_after=3.0)
@client.event
async def on_message_delete(message):
fmt = '{0.author.name} has deleted the message:\n{0.content}'
await client.send_message(message.channel, fmt.format(message))
async def on_message_delete(self, message):
fmt = '{0.author} has deleted the message: {0.content}'
await message.channel.send(fmt.format(message))
client = MyClient()
client.run('token')

30
examples/edits.py

@ -1,24 +1,20 @@
import discord
import asyncio
client = discord.Client()
class MyClient(discord.Client):
async def on_ready(self):
print('Connected!')
print('Username: {0.name}\nID: {0.id}'.format(self.user))
@client.event
async def on_ready():
print('Connected!')
print('Username: ' + client.user.name)
print('ID: ' + client.user.id)
async def on_message(self, message):
if message.content.startswith('!editme'):
msg = await message.channel.send('10')
await asyncio.sleep(3.0)
await msg.edit(content='40')
@client.event
async def on_message(message):
if message.content.startswith('!editme'):
msg = await client.send_message(message.author, '10')
await asyncio.sleep(3)
await client.edit_message(msg, '40')
@client.event
async def on_message_edit(before, after):
fmt = '**{0.author}** edited their message:\n{1.content}'
await client.send_message(after.channel, fmt.format(after, before))
async def on_message_edit(self, before, after):
fmt = '**{0.author}** edited their message:\n{0.content} -> {1.content}'
await before.channel.send(fmt.format(before, after))
client = MyClient()
client.run('token')

53
examples/guessing_game.py

@ -1,37 +1,32 @@
import discord
import random
client = discord.Client()
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('$guess'):
await client.send_message(message.channel, 'Guess a number between 1 to 10')
def guess_check(m):
return m.content.isdigit()
guess = await client.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 client.send_message(message.channel, fmt.format(answer))
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if int(guess.content) == answer:
await client.send_message(message.channel, 'You are right!')
else:
await client.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))
if message.content.startswith('$guess'):
await message.channel.send('Guess a number between 1 and 10.')
check = lambda m: m.content.isdigit()
guess = await self.wait_for_message(author=message.author, check=check, timeout=5.0)
answer = random.randint(1, 10)
if guess is not None:
await message.channel.send('Sorry, you took too long it was {}.'.format(answer))
return
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
if int(guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send('Oops. It is actually {}.'.format(answer))
client = MyClient()
client.run('token')

27
examples/new_member.py

@ -1,18 +1,15 @@
import discord
client = discord.Client()
@client.event
async def on_member_join(member):
server = member.server
fmt = 'Welcome {0.mention} to {1.name}!'
await client.send_message(server, fmt.format(member, server))
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_member_join(self, member):
guild = member.guild
await guild.default_channel.send('Welcome {0.mention} to {1.name}!'.format(member, guild))
client = MyClient()
client.run('token')

29
examples/reply.py

@ -1,22 +1,19 @@
import discord
client = discord.Client()
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
if message.content.startswith('!hello'):
await message.channel.send('Hello {0.author.mention}'.format(message))
client = MyClient()
client.run('token')

Loading…
Cancel
Save