Guest User

Discord 0-day by Fahrodab

a guest
Dec 30th, 2016
1,201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 109.51 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. """
  4. Discord Zeroday by FahroDab and LikorTes
  5. """
  6.  
  7. from . import __version__ as library_version
  8. from .user import User
  9. from .member import Member
  10. from .channel import Channel, PrivateChannel
  11. from .server import Server
  12. from .message import Message
  13. from .invite import Invite
  14. from .object import Object
  15. from .reaction import Reaction
  16. from .role import Role
  17. from .errors import *
  18. from .state import ConnectionState
  19. from .permissions import Permissions, PermissionOverwrite
  20. from . import utils, compat
  21. from .enums import ChannelType, ServerRegion, VerificationLevel, Status
  22. from .voice_client import VoiceClient
  23. from .iterators import LogsFromIterator
  24. from .gateway import *
  25. from .emoji import Emoji
  26. from .http import HTTPClient
  27.  
  28. import asyncio
  29. import aiohttp
  30. import websockets
  31.  
  32. import logging, traceback
  33. import sys, re, io, enum
  34. import tempfile, os, hashlib
  35. import itertools
  36. import datetime
  37. from collections import namedtuple
  38. from os.path import split as path_split
  39.  
  40. PY35 = sys.version_info >= (3, 5)
  41. log = logging.getLogger(__name__)
  42.  
  43. AppInfo = namedtuple('AppInfo', 'id name description icon owner')
  44. WaitedReaction = namedtuple('WaitedReaction', 'reaction user')
  45.  
  46. def app_info_icon_url(self):
  47. """Retrieves the application's icon_url if it exists. Empty string otherwise."""
  48. if not self.icon:
  49. return ''
  50.  
  51. return 'https://cdn.discordapp.com/app-icons/{0.id}/{0.icon}.jpg'.format(self)
  52.  
  53. AppInfo.icon_url = property(app_info_icon_url)
  54.  
  55. class WaitForType(enum.Enum):
  56. message = 0
  57. reaction = 1
  58.  
  59. ChannelPermissions = namedtuple('ChannelPermissions', 'target overwrite')
  60. ChannelPermissions.__new__.__defaults__ = (PermissionOverwrite(),)
  61.  
  62. class Client:
  63. """Represents a client connection that connects to Discord.
  64. This class is used to interact with the Discord WebSocket and API.
  65.  
  66. A number of options can be passed to the :class:`Client`.
  67.  
  68. .. _deque: https://docs.python.org/3.4/library/collections.html#collections.deque
  69. .. _event loop: https://docs.python.org/3/library/asyncio-eventloops.html
  70. .. _connector: http://aiohttp.readthedocs.org/en/stable/client_reference.html#connectors
  71. .. _ProxyConnector: http://aiohttp.readthedocs.org/en/stable/client_reference.html#proxyconnector
  72.  
  73. Parameters
  74. ----------
  75. max_messages : Optional[int]
  76. The maximum number of messages to store in :attr:`messages`.
  77. This defaults to 5000. Passing in `None` or a value less than 100
  78. will use the default instead of the passed in value.
  79. loop : Optional[event loop].
  80. The `event loop`_ to use for asynchronous operations. Defaults to ``None``,
  81. in which case the default event loop is used via ``asyncio.get_event_loop()``.
  82. cache_auth : Optional[bool]
  83. Indicates if :meth:`login` should cache the authentication tokens. Defaults
  84. to ``True``. The method in which the cache is written is done by writing to
  85. disk to a temporary directory.
  86. connector : aiohttp.BaseConnector
  87. The `connector`_ to use for connection pooling. Useful for proxies, e.g.
  88. with a `ProxyConnector`_.
  89. shard_id : Optional[int]
  90. Integer starting at 0 and less than shard_count.
  91. shard_count : Optional[int]
  92. The total number of shards.
  93.  
  94. Attributes
  95. -----------
  96. user : Optional[:class:`User`]
  97. Represents the connected client. None if not logged in.
  98. voice_clients : iterable of :class:`VoiceClient`
  99. Represents a list of voice connections. To connect to voice use
  100. :meth:`join_voice_channel`. To query the voice connection state use
  101. :meth:`is_voice_connected`.
  102. servers : iterable of :class:`Server`
  103. The servers that the connected client is a member of.
  104. private_channels : iterable of :class:`PrivateChannel`
  105. The private channels that the connected client is participating on.
  106. messages
  107. A deque_ of :class:`Message` that the client has received from all
  108. servers and private messages. The number of messages stored in this
  109. deque is controlled by the ``max_messages`` parameter.
  110. email
  111. The email used to login. This is only set if login is successful,
  112. otherwise it's None.
  113. ws
  114. The websocket gateway the client is currently connected to. Could be None.
  115. loop
  116. The `event loop`_ that the client uses for HTTP requests and websocket operations.
  117.  
  118. """
  119. def __init__(self, *, loop=None, **options):
  120. self.ws = None
  121. self.email = None
  122. self.loop = asyncio.get_event_loop() if loop is None else loop
  123. self._listeners = []
  124. self.cache_auth = options.get('cache_auth', True)
  125. self.shard_id = options.get('shard_id')
  126. self.shard_count = options.get('shard_count')
  127.  
  128. max_messages = options.get('max_messages')
  129. if max_messages is None or max_messages < 100:
  130. max_messages = 5000
  131.  
  132. self.connection = ConnectionState(self.dispatch, self.request_offline_members,
  133. self._syncer, max_messages, loop=self.loop)
  134.  
  135. connector = options.pop('connector', None)
  136. self.http = HTTPClient(connector, loop=self.loop)
  137.  
  138. self._closed = asyncio.Event(loop=self.loop)
  139. self._is_logged_in = asyncio.Event(loop=self.loop)
  140. self._is_ready = asyncio.Event(loop=self.loop)
  141.  
  142. if VoiceClient.warn_nacl:
  143. VoiceClient.warn_nacl = False
  144. log.warning("PyNaCl is not installed, voice will NOT be supported")
  145.  
  146. # internals
  147.  
  148. @asyncio.coroutine
  149. def _syncer(self, guilds):
  150. yield from self.ws.request_sync(guilds)
  151.  
  152. def _get_cache_filename(self, email):
  153. filename = hashlib.md5(email.encode('utf-8')).hexdigest()
  154. return os.path.join(tempfile.gettempdir(), 'discord_py', filename)
  155.  
  156. def _get_cache_token(self, email, password):
  157. try:
  158. log.info('attempting to login via cache')
  159. cache_file = self._get_cache_filename(email)
  160. self.email = email
  161. with open(cache_file, 'r') as f:
  162. log.info('login cache file found')
  163. return f.read()
  164.  
  165. # at this point our check failed
  166. # so we have to login and get the proper token and then
  167. # redo the cache
  168. except OSError:
  169. log.info('a problem occurred while opening login cache')
  170. return None # file not found et al
  171.  
  172. def _update_cache(self, email, password):
  173. try:
  174. cache_file = self._get_cache_filename(email)
  175. os.makedirs(os.path.dirname(cache_file), exist_ok=True)
  176. with os.fdopen(os.open(cache_file, os.O_WRONLY | os.O_CREAT, 0o0600), 'w') as f:
  177. log.info('updating login cache')
  178. f.write(self.http.token)
  179. except OSError:
  180. log.info('a problem occurred while updating the login cache')
  181. pass
  182.  
  183. def handle_reaction_add(self, reaction, user):
  184. removed = []
  185. for i, (condition, future, event_type) in enumerate(self._listeners):
  186. if event_type is not WaitForType.reaction:
  187. continue
  188.  
  189. if future.cancelled():
  190. removed.append(i)
  191. continue
  192.  
  193. try:
  194. result = condition(reaction, user)
  195. except Exception as e:
  196. future.set_exception(e)
  197. removed.append(i)
  198. else:
  199. if result:
  200. future.set_result(WaitedReaction(reaction, user))
  201. removed.append(i)
  202.  
  203.  
  204. for idx in reversed(removed):
  205. del self._listeners[idx]
  206.  
  207. def handle_message(self, message):
  208. removed = []
  209. for i, (condition, future, event_type) in enumerate(self._listeners):
  210. if event_type is not WaitForType.message:
  211. continue
  212.  
  213. if future.cancelled():
  214. removed.append(i)
  215. continue
  216.  
  217. try:
  218. result = condition(message)
  219. except Exception as e:
  220. future.set_exception(e)
  221. removed.append(i)
  222. else:
  223. if result:
  224. future.set_result(message)
  225. removed.append(i)
  226.  
  227.  
  228. for idx in reversed(removed):
  229. del self._listeners[idx]
  230.  
  231. def handle_ready(self):
  232. self._is_ready.set()
  233.  
  234. def _resolve_invite(self, invite):
  235. if isinstance(invite, Invite) or isinstance(invite, Object):
  236. return invite.id
  237. else:
  238. rx = r'(?:https?\:\/\/)?discord\.gg\/(.+)'
  239. m = re.match(rx, invite)
  240. if m:
  241. return m.group(1)
  242. return invite
  243.  
  244. @asyncio.coroutine
  245. def _resolve_destination(self, destination):
  246. if isinstance(destination, Channel):
  247. return destination.id, destination.server.id
  248. elif isinstance(destination, PrivateChannel):
  249. return destination.id, None
  250. elif isinstance(destination, Server):
  251. return destination.id, destination.id
  252. elif isinstance(destination, User):
  253. found = self.connection._get_private_channel_by_user(destination.id)
  254. if found is None:
  255. # Couldn't find the user, so start a PM with them first.
  256. channel = yield from self.start_private_message(destination)
  257. return channel.id, None
  258. else:
  259. return found.id, None
  260. elif isinstance(destination, Object):
  261. found = self.get_channel(destination.id)
  262. if found is not None:
  263. return (yield from self._resolve_destination(found))
  264.  
  265. # couldn't find it in cache so YOLO
  266. return destination.id, destination.id
  267. else:
  268. fmt = 'Destination must be Channel, PrivateChannel, User, or Object. Received {0.__class__.__name__}'
  269. raise InvalidArgument(fmt.format(destination))
  270.  
  271. def __getattr__(self, name):
  272. if name in ('user', 'servers', 'private_channels', 'messages', 'voice_clients'):
  273. return getattr(self.connection, name)
  274. else:
  275. msg = "'{}' object has no attribute '{}'"
  276. raise AttributeError(msg.format(self.__class__, name))
  277.  
  278. def __setattr__(self, name, value):
  279. if name in ('user', 'servers', 'private_channels', 'messages', 'voice_clients'):
  280. return setattr(self.connection, name, value)
  281. else:
  282. object.__setattr__(self, name, value)
  283.  
  284. @asyncio.coroutine
  285. def _run_event(self, event, *args, **kwargs):
  286. try:
  287. yield from getattr(self, event)(*args, **kwargs)
  288. except asyncio.CancelledError:
  289. pass
  290. except Exception:
  291. try:
  292. yield from self.on_error(event, *args, **kwargs)
  293. except asyncio.CancelledError:
  294. pass
  295.  
  296. def dispatch(self, event, *args, **kwargs):
  297. log.debug('Dispatching event {}'.format(event))
  298. method = 'on_' + event
  299. handler = 'handle_' + event
  300.  
  301. if hasattr(self, handler):
  302. getattr(self, handler)(*args, **kwargs)
  303.  
  304. if hasattr(self, method):
  305. compat.create_task(self._run_event(method, *args, **kwargs), loop=self.loop)
  306.  
  307. @asyncio.coroutine
  308. def on_error(self, event_method, *args, **kwargs):
  309. """|coro|
  310.  
  311. The default error handler provided by the client.
  312.  
  313. By default this prints to ``sys.stderr`` however it could be
  314. overridden to have a different implementation.
  315. Check :func:`discord.on_error` for more details.
  316. """
  317. print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
  318. traceback.print_exc()
  319.  
  320. # login state management
  321.  
  322. @asyncio.coroutine
  323. def _login_1(self, token, **kwargs):
  324. log.info('logging in using static token')
  325. is_bot = kwargs.pop('bot', True)
  326. data = yield from self.http.static_login(token, bot=is_bot)
  327. self.email = data.get('email', None)
  328. self.connection.is_bot = is_bot
  329. self._is_logged_in.set()
  330.  
  331. @asyncio.coroutine
  332. def _login_2(self, email, password, **kwargs):
  333. # attempt to read the token from cache
  334. self.connection.is_bot = False
  335.  
  336. if self.cache_auth:
  337. token = self._get_cache_token(email, password)
  338. try:
  339. yield from self.http.static_login(token, bot=False)
  340. except:
  341. log.info('cache auth token is out of date')
  342. else:
  343. self._is_logged_in.set()
  344. return
  345.  
  346.  
  347. yield from self.http.email_login(email, password)
  348. self.email = email
  349. self._is_logged_in.set()
  350.  
  351. # since we went through all this trouble
  352. # let's make sure we don't have to do it again
  353. if self.cache_auth:
  354. self._update_cache(email, password)
  355.  
  356. @asyncio.coroutine
  357. def login(self, *args, **kwargs):
  358. """|coro|
  359.  
  360. Logs in the client with the specified credentials.
  361.  
  362. This function can be used in two different ways.
  363.  
  364. .. code-block:: python
  365.  
  366. await client.login('token')
  367.  
  368. # or
  369.  
  370. await client.login('email', 'password')
  371.  
  372. More than 2 parameters or less than 1 parameter raises a
  373. :exc:`TypeError`.
  374.  
  375. Parameters
  376. -----------
  377. bot : bool
  378. Keyword argument that specifies if the account logging on is a bot
  379. token or not. Only useful for logging in with a static token.
  380. Ignored for the email and password combo. Defaults to ``True``.
  381.  
  382. Raises
  383. ------
  384. LoginFailure
  385. The wrong credentials are passed.
  386. HTTPException
  387. An unknown HTTP related error occurred,
  388. usually when it isn't 200 or the known incorrect credentials
  389. passing status code.
  390. TypeError
  391. The incorrect number of parameters is passed.
  392. """
  393.  
  394. n = len(args)
  395. if n in (2, 1):
  396. yield from getattr(self, '_login_' + str(n))(*args, **kwargs)
  397. else:
  398. raise TypeError('login() takes 1 or 2 positional arguments but {} were given'.format(n))
  399.  
  400. @asyncio.coroutine
  401. def logout(self):
  402. """|coro|
  403.  
  404. Logs out of Discord and closes all connections.
  405. """
  406. yield from self.close()
  407. self._is_logged_in.clear()
  408.  
  409. @asyncio.coroutine
  410. def connect(self):
  411. """|coro|
  412.  
  413. Creates a websocket connection and lets the websocket listen
  414. to messages from discord.
  415.  
  416. Raises
  417. -------
  418. GatewayNotFound
  419. If the gateway to connect to discord is not found. Usually if this
  420. is thrown then there is a discord API outage.
  421. ConnectionClosed
  422. The websocket connection has been terminated.
  423. """
  424. self.ws = yield from DiscordWebSocket.from_client(self)
  425.  
  426. while not self.is_closed:
  427. try:
  428. yield from self.ws.poll_event()
  429. except (ReconnectWebSocket, ResumeWebSocket) as e:
  430. resume = type(e) is ResumeWebSocket
  431. log.info('Got ' + type(e).__name__)
  432. self.ws = yield from DiscordWebSocket.from_client(self, resume=resume)
  433. except ConnectionClosed as e:
  434. yield from self.close()
  435. if e.code != 1000:
  436. raise
  437.  
  438. @asyncio.coroutine
  439. def close(self):
  440. """|coro|
  441.  
  442. Closes the connection to discord.
  443. """
  444. if self.is_closed:
  445. return
  446.  
  447. for voice in list(self.voice_clients):
  448. try:
  449. yield from voice.disconnect()
  450. except:
  451. # if an error happens during disconnects, disregard it.
  452. pass
  453.  
  454. self.connection._remove_voice_client(voice.server.id)
  455.  
  456. if self.ws is not None and self.ws.open:
  457. yield from self.ws.close()
  458.  
  459.  
  460. yield from self.http.close()
  461. self._closed.set()
  462. self._is_ready.clear()
  463.  
  464. @asyncio.coroutine
  465. def start(self, *args, **kwargs):
  466. """|coro|
  467.  
  468. A shorthand coroutine for :meth:`login` + :meth:`connect`.
  469. """
  470. yield from self.login(*args, **kwargs)
  471. yield from self.connect()
  472.  
  473. def run(self, *args, **kwargs):
  474. """A blocking call that abstracts away the `event loop`_
  475. initialisation from you.
  476.  
  477. If you want more control over the event loop then this
  478. function should not be used. Use :meth:`start` coroutine
  479. or :meth:`connect` + :meth:`login`.
  480.  
  481. Roughly Equivalent to: ::
  482.  
  483. try:
  484. loop.run_until_complete(start(*args, **kwargs))
  485. except KeyboardInterrupt:
  486. loop.run_until_complete(logout())
  487. # cancel all tasks lingering
  488. finally:
  489. loop.close()
  490.  
  491. Warning
  492. --------
  493. This function must be the last function to call due to the fact that it
  494. is blocking. That means that registration of events or anything being
  495. called after this function call will not execute until it returns.
  496. """
  497.  
  498. try:
  499. self.loop.run_until_complete(self.start(*args, **kwargs))
  500. except KeyboardInterrupt:
  501. self.loop.run_until_complete(self.logout())
  502. pending = asyncio.Task.all_tasks(loop=self.loop)
  503. gathered = asyncio.gather(*pending, loop=self.loop)
  504. try:
  505. gathered.cancel()
  506. self.loop.run_until_complete(gathered)
  507.  
  508. # we want to retrieve any exceptions to make sure that
  509. # they don't nag us about it being un-retrieved.
  510. gathered.exception()
  511. except:
  512. pass
  513. finally:
  514. self.loop.close()
  515.  
  516. # properties
  517.  
  518. @property
  519. def is_logged_in(self):
  520. """bool: Indicates if the client has logged in successfully."""
  521. return self._is_logged_in.is_set()
  522.  
  523. @property
  524. def is_closed(self):
  525. """bool: Indicates if the websocket connection is closed."""
  526. return self._closed.is_set()
  527.  
  528. # helpers/getters
  529.  
  530. def get_channel(self, id):
  531. """Returns a :class:`Channel` or :class:`PrivateChannel` with the following ID. If not found, returns None."""
  532. return self.connection.get_channel(id)
  533.  
  534. def get_server(self, id):
  535. """Returns a :class:`Server` with the given ID. If not found, returns None."""
  536. return self.connection._get_server(id)
  537.  
  538. def get_all_emojis(self):
  539. """Returns a generator with every :class:`Emoji` the client can see."""
  540. for server in self.servers:
  541. for emoji in server.emojis:
  542. yield emoji
  543.  
  544. def get_all_channels(self):
  545. """A generator that retrieves every :class:`Channel` the client can 'access'.
  546.  
  547. This is equivalent to: ::
  548.  
  549. for server in client.servers:
  550. for channel in server.channels:
  551. yield channel
  552.  
  553. Note
  554. -----
  555. Just because you receive a :class:`Channel` does not mean that
  556. you can communicate in said channel. :meth:`Channel.permissions_for` should
  557. be used for that.
  558. """
  559.  
  560. for server in self.servers:
  561. for channel in server.channels:
  562. yield channel
  563.  
  564. def get_all_members(self):
  565. """Returns a generator with every :class:`Member` the client can see.
  566.  
  567. This is equivalent to: ::
  568.  
  569. for server in client.servers:
  570. for member in server.members:
  571. yield member
  572.  
  573. """
  574. for server in self.servers:
  575. for member in server.members:
  576. yield member
  577.  
  578. # listeners/waiters
  579.  
  580. @asyncio.coroutine
  581. def wait_until_ready(self):
  582. """|coro|
  583.  
  584. This coroutine waits until the client is all ready. This could be considered
  585. another way of asking for :func:`discord.on_ready` except meant for your own
  586. background tasks.
  587. """
  588. yield from self._is_ready.wait()
  589.  
  590. @asyncio.coroutine
  591. def wait_until_login(self):
  592. """|coro|
  593.  
  594. This coroutine waits until the client is logged on successfully. This
  595. is different from waiting until the client's state is all ready. For
  596. that check :func:`discord.on_ready` and :meth:`wait_until_ready`.
  597. """
  598. yield from self._is_logged_in.wait()
  599.  
  600. @asyncio.coroutine
  601. def wait_for_message(self, timeout=None, *, author=None, channel=None, content=None, check=None):
  602. """|coro|
  603.  
  604. Waits for a message reply from Discord. This could be seen as another
  605. :func:`discord.on_message` event outside of the actual event. This could
  606. also be used for follow-ups and easier user interactions.
  607.  
  608. The keyword arguments passed into this function are combined using the logical and
  609. operator. The ``check`` keyword argument can be used to pass in more complicated
  610. checks and must be a regular function (not a coroutine).
  611.  
  612. The ``timeout`` parameter is passed into `asyncio.wait_for`_. By default, it
  613. does not timeout. Instead of throwing ``asyncio.TimeoutError`` the coroutine
  614. catches the exception and returns ``None`` instead of a :class:`Message`.
  615.  
  616. If the ``check`` predicate throws an exception, then the exception is propagated.
  617.  
  618. This function returns the **first message that meets the requirements**.
  619.  
  620. .. _asyncio.wait_for: https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for
  621.  
  622. Examples
  623. ----------
  624.  
  625. Basic example:
  626.  
  627. .. code-block:: python
  628. :emphasize-lines: 5
  629.  
  630. @client.event
  631. async def on_message(message):
  632. if message.content.startswith('$greet'):
  633. await client.send_message(message.channel, 'Say hello')
  634. msg = await client.wait_for_message(author=message.author, content='hello')
  635. await client.send_message(message.channel, 'Hello.')
  636.  
  637. Asking for a follow-up question:
  638.  
  639. .. code-block:: python
  640. :emphasize-lines: 6
  641.  
  642. @client.event
  643. async def on_message(message):
  644. if message.content.startswith('$start'):
  645. await client.send_message(message.channel, 'Type $stop 4 times.')
  646. for i in range(4):
  647. msg = await client.wait_for_message(author=message.author, content='$stop')
  648. fmt = '{} left to go...'
  649. await client.send_message(message.channel, fmt.format(3 - i))
  650.  
  651. await client.send_message(message.channel, 'Good job!')
  652.  
  653. Advanced filters using ``check``:
  654.  
  655. .. code-block:: python
  656. :emphasize-lines: 9
  657.  
  658. @client.event
  659. async def on_message(message):
  660. if message.content.startswith('$cool'):
  661. await client.send_message(message.channel, 'Who is cool? Type $name namehere')
  662.  
  663. def check(msg):
  664. return msg.content.startswith('$name')
  665.  
  666. message = await client.wait_for_message(author=message.author, check=check)
  667. name = message.content[len('$name'):].strip()
  668. await client.send_message(message.channel, '{} is cool indeed'.format(name))
  669.  
  670.  
  671. Parameters
  672. -----------
  673. timeout : float
  674. The number of seconds to wait before returning ``None``.
  675. author : :class:`Member` or :class:`User`
  676. The author the message must be from.
  677. channel : :class:`Channel` or :class:`PrivateChannel` or :class:`Object`
  678. The channel the message must be from.
  679. content : str
  680. The exact content the message must have.
  681. check : function
  682. A predicate for other complicated checks. The predicate must take
  683. a :class:`Message` as its only parameter.
  684.  
  685. Returns
  686. --------
  687. :class:`Message`
  688. The message that you requested for.
  689. """
  690.  
  691. def predicate(message):
  692. result = True
  693. if author is not None:
  694. result = result and message.author == author
  695.  
  696. if content is not None:
  697. result = result and message.content == content
  698.  
  699. if channel is not None:
  700. result = result and message.channel.id == channel.id
  701.  
  702. if callable(check):
  703. # the exception thrown by check is propagated through the future.
  704. result = result and check(message)
  705.  
  706. return result
  707.  
  708. future = asyncio.Future(loop=self.loop)
  709. self._listeners.append((predicate, future, WaitForType.message))
  710. try:
  711. message = yield from asyncio.wait_for(future, timeout, loop=self.loop)
  712. except asyncio.TimeoutError:
  713. message = None
  714. return message
  715.  
  716.  
  717. @asyncio.coroutine
  718. def wait_for_reaction(self, emoji=None, *, user=None, timeout=None, message=None, check=None):
  719. """|coro|
  720.  
  721. Waits for a message reaction from Discord. This is similar to :meth:`wait_for_message`
  722. and could be seen as another :func:`on_reaction_add` event outside of the actual event.
  723. This could be used for follow up situations.
  724.  
  725. Similar to :meth:`wait_for_message`, the keyword arguments are combined using logical
  726. AND operator. The ``check`` keyword argument can be used to pass in more complicated
  727. checks and must a regular function taking in two arguments, ``(reaction, user)``. It
  728. must not be a coroutine.
  729.  
  730. The ``timeout`` parameter is passed into asyncio.wait_for. By default, it
  731. does not timeout. Instead of throwing ``asyncio.TimeoutError`` the coroutine
  732. catches the exception and returns ``None`` instead of a the ``(reaction, user)``
  733. tuple.
  734.  
  735. If the ``check`` predicate throws an exception, then the exception is propagated.
  736.  
  737. The ``emoji`` parameter can be either a :class:`Emoji`, a ``str`` representing
  738. an emoji, or a sequence of either type. If the ``emoji`` parameter is a sequence
  739. then the first reaction emoji that is in the list is returned. If ``None`` is
  740. passed then the first reaction emoji used is returned.
  741.  
  742. This function returns the **first reaction that meets the requirements**.
  743.  
  744. Examples
  745. ---------
  746.  
  747. Basic Example:
  748.  
  749. .. code-block:: python
  750.  
  751. @client.event
  752. async def on_message(message):
  753. if message.content.startswith('$react'):
  754. msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.')
  755. res = await client.wait_for_reaction(['\N{THUMBS UP SIGN}', '\N{THUMBS DOWN SIGN}'], message=msg)
  756. await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
  757.  
  758. Checking for reaction emoji regardless of skin tone:
  759.  
  760. .. code-block:: python
  761.  
  762. @client.event
  763. async def on_message(message):
  764. if message.content.startswith('$react'):
  765. msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.')
  766.  
  767. def check(reaction, user):
  768. e = str(reaction.emoji)
  769. return e.startswith(('\N{THUMBS UP SIGN}', '\N{THUMBS DOWN SIGN}'))
  770.  
  771. res = await client.wait_for_reaction(message=msg, check=check)
  772. await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
  773.  
  774. Parameters
  775. -----------
  776. timeout: float
  777. The number of seconds to wait before returning ``None``.
  778. user: :class:`Member` or :class:`User`
  779. The user the reaction must be from.
  780. emoji: str or :class:`Emoji` or sequence
  781. The emoji that we are waiting to react with.
  782. message: :class:`Message`
  783. The message that we want the reaction to be from.
  784. check: function
  785. A predicate for other complicated checks. The predicate must take
  786. ``(reaction, user)`` as its two parameters, which ``reaction`` being a
  787. :class:`Reaction` and ``user`` being either a :class:`User` or a
  788. :class:`Member`.
  789.  
  790. Returns
  791. --------
  792. namedtuple
  793. A namedtuple with attributes ``reaction`` and ``user`` similar to :func:`on_reaction_add`.
  794. """
  795.  
  796. if emoji is None:
  797. emoji_check = lambda r: True
  798. elif isinstance(emoji, (str, Emoji)):
  799. emoji_check = lambda r: r.emoji == emoji
  800. else:
  801. emoji_check = lambda r: r.emoji in emoji
  802.  
  803. def predicate(reaction, reaction_user):
  804. result = emoji_check(reaction)
  805.  
  806. if message is not None:
  807. result = result and message.id == reaction.message.id
  808.  
  809. if user is not None:
  810. result = result and user.id == reaction_user.id
  811.  
  812. if callable(check):
  813. # the exception thrown by check is propagated through the future.
  814. result = result and check(reaction, reaction_user)
  815.  
  816. return result
  817.  
  818. future = asyncio.Future(loop=self.loop)
  819. self._listeners.append((predicate, future, WaitForType.reaction))
  820. try:
  821. return (yield from asyncio.wait_for(future, timeout, loop=self.loop))
  822. except asyncio.TimeoutError:
  823. return None
  824.  
  825. # event registration
  826.  
  827. def event(self, coro):
  828. """A decorator that registers an event to listen to.
  829.  
  830. You can find more info about the events on the :ref:`documentation below <discord-api-events>`.
  831.  
  832. The events must be a |corourl|_, if not, :exc:`ClientException` is raised.
  833.  
  834. Examples
  835. ---------
  836.  
  837. Using the basic :meth:`event` decorator: ::
  838.  
  839. @client.event
  840. @asyncio.coroutine
  841. def on_ready():
  842. print('Ready!')
  843.  
  844. Saving characters by using the :meth:`async_event` decorator: ::
  845.  
  846. @client.async_event
  847. def on_ready():
  848. print('Ready!')
  849.  
  850. """
  851.  
  852. if not asyncio.iscoroutinefunction(coro):
  853. raise ClientException('event registered must be a coroutine function')
  854.  
  855. setattr(self, coro.__name__, coro)
  856. log.info('{0.__name__} has successfully been registered as an event'.format(coro))
  857. return coro
  858.  
  859. def async_event(self, coro):
  860. """A shorthand decorator for ``asyncio.coroutine`` + :meth:`event`."""
  861. if not asyncio.iscoroutinefunction(coro):
  862. coro = asyncio.coroutine(coro)
  863.  
  864. return self.event(coro)
  865.  
  866. # Message sending/management
  867.  
  868. @asyncio.coroutine
  869. def start_private_message(self, user):
  870. """|coro|
  871.  
  872. Starts a private message with the user. This allows you to
  873. :meth:`send_message` to the user.
  874.  
  875. Note
  876. -----
  877. This method should rarely be called as :meth:`send_message`
  878. does it automatically for you.
  879.  
  880. Parameters
  881. -----------
  882. user : :class:`User`
  883. The user to start the private message with.
  884.  
  885. Raises
  886. ------
  887. HTTPException
  888. The request failed.
  889. InvalidArgument
  890. The user argument was not of :class:`User`.
  891. """
  892.  
  893. if not isinstance(user, User):
  894. raise InvalidArgument('user argument must be a User')
  895.  
  896. data = yield from self.http.start_private_message(user.id)
  897. channel = PrivateChannel(me=self.user, **data)
  898. self.connection._add_private_channel(channel)
  899. return channel
  900.  
  901. @asyncio.coroutine
  902. def add_reaction(self, message, emoji):
  903. """|coro|
  904.  
  905. Add a reaction to the given message.
  906.  
  907. The message must be a :class:`Message` that exists. emoji may be a unicode emoji,
  908. or a custom server :class:`Emoji`.
  909.  
  910. Parameters
  911. ------------
  912. message : :class:`Message`
  913. The message to react to.
  914. emoji : :class:`Emoji` or str
  915. The emoji to react with.
  916.  
  917. Raises
  918. --------
  919. HTTPException
  920. Adding the reaction failed.
  921. Forbidden
  922. You do not have the proper permissions to react to the message.
  923. NotFound
  924. The message or emoji you specified was not found.
  925. InvalidArgument
  926. The message or emoji parameter is invalid.
  927. """
  928. if not isinstance(message, Message):
  929. raise InvalidArgument('message argument must be a Message')
  930. if not isinstance(emoji, (str, Emoji)):
  931. raise InvalidArgument('emoji argument must be a string or Emoji')
  932.  
  933. if isinstance(emoji, Emoji):
  934. emoji = '{}:{}'.format(emoji.name, emoji.id)
  935.  
  936. yield from self.http.add_reaction(message.id, message.channel.id, emoji)
  937.  
  938. @asyncio.coroutine
  939. def remove_reaction(self, message, emoji, member):
  940. """|coro|
  941.  
  942. Remove a reaction by the member from the given message.
  943.  
  944. If member != server.me, you need Manage Messages to remove the reaction.
  945.  
  946. The message must be a :class:`Message` that exists. emoji may be a unicode emoji,
  947. or a custom server :class:`Emoji`.
  948.  
  949. Parameters
  950. ------------
  951. message : :class:`Message`
  952. The message.
  953. emoji : :class:`Emoji` or str
  954. The emoji to remove.
  955. member : :class:`Member`
  956. The member for which to delete the reaction.
  957.  
  958. Raises
  959. --------
  960. HTTPException
  961. Removing the reaction failed.
  962. Forbidden
  963. You do not have the proper permissions to remove the reaction.
  964. NotFound
  965. The message or emoji you specified was not found.
  966. InvalidArgument
  967. The message or emoji parameter is invalid.
  968. """
  969. if not isinstance(message, Message):
  970. raise InvalidArgument('message argument must be a Message')
  971. if not isinstance(emoji, (str, Emoji)):
  972. raise InvalidArgument('emoji must be a string or Emoji')
  973.  
  974. if isinstance(emoji, Emoji):
  975. emoji = '{}:{}'.format(emoji.name, emoji.id)
  976.  
  977. if member == self.user:
  978. member_id = '@me'
  979. else:
  980. member_id = member.id
  981.  
  982. yield from self.http.remove_reaction(message.id, message.channel.id, emoji, member_id)
  983.  
  984. @asyncio.coroutine
  985. def get_reaction_users(self, reaction, limit=100, after=None):
  986. """|coro|
  987.  
  988. Get the users that added a reaction to a message.
  989.  
  990. Parameters
  991. ------------
  992. reaction : :class:`Reaction`
  993. The reaction to retrieve users for.
  994. limit : int
  995. The maximum number of results to return.
  996. after : :class:`Member` or :class:`Object`
  997. For pagination, reactions are sorted by member.
  998.  
  999. Raises
  1000. --------
  1001. HTTPException
  1002. Getting the users for the reaction failed.
  1003. NotFound
  1004. The message or emoji you specified was not found.
  1005. InvalidArgument
  1006. The reaction parameter is invalid.
  1007. """
  1008. if not isinstance(reaction, Reaction):
  1009. raise InvalidArgument('reaction must be a Reaction')
  1010.  
  1011. emoji = reaction.emoji
  1012.  
  1013. if isinstance(emoji, Emoji):
  1014. emoji = '{}:{}'.format(emoji.name, emoji.id)
  1015.  
  1016. if after:
  1017. after = after.id
  1018.  
  1019. data = yield from self.http.get_reaction_users(
  1020. reaction.message.id, reaction.message.channel.id,
  1021. emoji, limit, after=after)
  1022.  
  1023. return [User(**user) for user in data]
  1024.  
  1025. @asyncio.coroutine
  1026. def clear_reactions(self, message):
  1027. """|coro|
  1028.  
  1029. Removes all the reactions from a given message.
  1030.  
  1031. You need Manage Messages permission to use this.
  1032.  
  1033. Parameters
  1034. -----------
  1035. message: :class:`Message`
  1036. The message to remove all reactions from.
  1037.  
  1038. Raises
  1039. --------
  1040. HTTPException
  1041. Removing the reactions failed.
  1042. Forbidden
  1043. You do not have the proper permissions to remove all the reactions.
  1044. """
  1045. yield from self.http.clear_reactions(message.id, message.channel.id)
  1046.  
  1047. @asyncio.coroutine
  1048. def send_message(self, destination, content=None, *, tts=False, embed=None):
  1049. """|coro|
  1050.  
  1051. Sends a message to the destination given with the content given.
  1052.  
  1053. The destination could be a :class:`Channel`, :class:`PrivateChannel` or :class:`Server`.
  1054. For convenience it could also be a :class:`User`. If it's a :class:`User` or :class:`PrivateChannel`
  1055. then it sends the message via private message, otherwise it sends the message to the channel.
  1056. If the destination is a :class:`Server` then it's equivalent to calling
  1057. :attr:`Server.default_channel` and sending it there.
  1058.  
  1059. If it is a :class:`Object` instance then it is assumed to be the
  1060. destination ID. The destination ID is a *channel* so passing in a user
  1061. ID will not be a valid destination.
  1062.  
  1063. .. versionchanged:: 0.9.0
  1064. ``str`` being allowed was removed and replaced with :class:`Object`.
  1065.  
  1066. The content must be a type that can convert to a string through ``str(content)``.
  1067. If the content is set to ``None`` (the default), then the ``embed`` parameter must
  1068. be provided.
  1069.  
  1070. If the ``embed`` parameter is provided, it must be of type :class:`Embed` and
  1071. it must be a rich embed type.
  1072.  
  1073. Parameters
  1074. ------------
  1075. destination
  1076. The location to send the message.
  1077. content
  1078. The content of the message to send. If this is missing,
  1079. then the ``embed`` parameter must be present.
  1080. tts : bool
  1081. Indicates if the message should be sent using text-to-speech.
  1082. embed: :class:`Embed`
  1083. The rich embed for the content.
  1084.  
  1085. Raises
  1086. --------
  1087. HTTPException
  1088. Sending the message failed.
  1089. Forbidden
  1090. You do not have the proper permissions to send the message.
  1091. NotFound
  1092. The destination was not found and hence is invalid.
  1093. InvalidArgument
  1094. The destination parameter is invalid.
  1095.  
  1096. Examples
  1097. ----------
  1098.  
  1099. Sending a regular message:
  1100.  
  1101. .. code-block:: python
  1102.  
  1103. await client.send_message(message.channel, 'Hello')
  1104.  
  1105. Sending a TTS message:
  1106.  
  1107. .. code-block:: python
  1108.  
  1109. await client.send_message(message.channel, 'Goodbye.', tts=True)
  1110.  
  1111. Sending an embed message:
  1112.  
  1113. .. code-block:: python
  1114.  
  1115. em = discord.Embed(title='My Embed Title', description='My Embed Content.', colour=0xDEADBF)
  1116. em.set_author(name='Someone', icon_url=client.user.default_avatar_url)
  1117. await client.send_message(message.channel, embed=em)
  1118.  
  1119. Returns
  1120. ---------
  1121. :class:`Message`
  1122. The message that was sent.
  1123. """
  1124.  
  1125. channel_id, guild_id = yield from self._resolve_destination(destination)
  1126.  
  1127. content = str(content) if content else None
  1128.  
  1129. if embed is not None:
  1130. embed = embed.to_dict()
  1131.  
  1132. data = yield from self.http.send_message(channel_id, content, guild_id=guild_id, tts=tts, embed=embed)
  1133. channel = self.get_channel(data.get('channel_id'))
  1134. message = self.connection._create_message(channel=channel, **data)
  1135. return message
  1136.  
  1137. @asyncio.coroutine
  1138. def send_typing(self, destination):
  1139. """|coro|
  1140.  
  1141. Send a *typing* status to the destination.
  1142.  
  1143. *Typing* status will go away after 10 seconds, or after a message is sent.
  1144.  
  1145. The destination parameter follows the same rules as :meth:`send_message`.
  1146.  
  1147. Parameters
  1148. ----------
  1149. destination
  1150. The location to send the typing update.
  1151. """
  1152.  
  1153. channel_id, guild_id = yield from self._resolve_destination(destination)
  1154. yield from self.http.send_typing(channel_id)
  1155.  
  1156. @asyncio.coroutine
  1157. def send_file(self, destination, fp, *, filename=None, content=None, tts=False):
  1158. """|coro|
  1159.  
  1160. Sends a message to the destination given with the file given.
  1161.  
  1162. The destination parameter follows the same rules as :meth:`send_message`.
  1163.  
  1164. The ``fp`` parameter should be either a string denoting the location for a
  1165. file or a *file-like object*. The *file-like object* passed is **not closed**
  1166. at the end of execution. You are responsible for closing it yourself.
  1167.  
  1168. .. note::
  1169.  
  1170. If the file-like object passed is opened via ``open`` then the modes
  1171. 'rb' should be used.
  1172.  
  1173. The ``filename`` parameter is the filename of the file.
  1174. If this is not given then it defaults to ``fp.name`` or if ``fp`` is a string
  1175. then the ``filename`` will default to the string given. You can overwrite
  1176. this value by passing this in.
  1177.  
  1178. Parameters
  1179. ------------
  1180. destination
  1181. The location to send the message.
  1182. fp
  1183. The *file-like object* or file path to send.
  1184. filename : str
  1185. The filename of the file. Defaults to ``fp.name`` if it's available.
  1186. content
  1187. The content of the message to send along with the file. This is
  1188. forced into a string by a ``str(content)`` call.
  1189. tts : bool
  1190. If the content of the message should be sent with TTS enabled.
  1191.  
  1192. Raises
  1193. -------
  1194. HTTPException
  1195. Sending the file failed.
  1196.  
  1197. Returns
  1198. --------
  1199. :class:`Message`
  1200. The message sent.
  1201. """
  1202.  
  1203. channel_id, guild_id = yield from self._resolve_destination(destination)
  1204.  
  1205. try:
  1206. with open(fp, 'rb') as f:
  1207. buffer = io.BytesIO(f.read())
  1208. if filename is None:
  1209. _, filename = path_split(fp)
  1210. except TypeError:
  1211. buffer = fp
  1212.  
  1213. data = yield from self.http.send_file(channel_id, buffer, guild_id=guild_id,
  1214. filename=filename, content=content, tts=tts)
  1215. channel = self.get_channel(data.get('channel_id'))
  1216. message = self.connection._create_message(channel=channel, **data)
  1217. return message
  1218.  
  1219. @asyncio.coroutine
  1220. def delete_message(self, message):
  1221. """|coro|
  1222.  
  1223. Deletes a :class:`Message`.
  1224.  
  1225. Your own messages could be deleted without any proper permissions. However to
  1226. delete other people's messages, you need the proper permissions to do so.
  1227.  
  1228. Parameters
  1229. -----------
  1230. message : :class:`Message`
  1231. The message to delete.
  1232.  
  1233. Raises
  1234. ------
  1235. Forbidden
  1236. You do not have proper permissions to delete the message.
  1237. HTTPException
  1238. Deleting the message failed.
  1239. """
  1240. channel = message.channel
  1241. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1242. yield from self.http.delete_message(channel.id, message.id, guild_id)
  1243.  
  1244. @asyncio.coroutine
  1245. def delete_messages(self, messages):
  1246. """|coro|
  1247.  
  1248. Deletes a list of messages. This is similar to :func:`delete_message`
  1249. except it bulk deletes multiple messages.
  1250.  
  1251. The channel to check where the message is deleted from is handled via
  1252. the first element of the iterable's ``.channel.id`` attributes. If the
  1253. channel is not consistent throughout the entire sequence, then an
  1254. :exc:`HTTPException` will be raised.
  1255.  
  1256. Usable only by bot accounts.
  1257.  
  1258. Parameters
  1259. -----------
  1260. messages : iterable of :class:`Message`
  1261. An iterable of messages denoting which ones to bulk delete.
  1262.  
  1263. Raises
  1264. ------
  1265. ClientException
  1266. The number of messages to delete is less than 2 or more than 100.
  1267. Forbidden
  1268. You do not have proper permissions to delete the messages or
  1269. you're not using a bot account.
  1270. HTTPException
  1271. Deleting the messages failed.
  1272. """
  1273.  
  1274. messages = list(messages)
  1275. if len(messages) > 100 or len(messages) < 2:
  1276. raise ClientException('Can only delete messages in the range of [2, 100]')
  1277.  
  1278. channel = messages[0].channel
  1279. message_ids = [m.id for m in messages]
  1280. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1281. yield from self.http.delete_messages(channel.id, message_ids, guild_id)
  1282.  
  1283. @asyncio.coroutine
  1284. def purge_from(self, channel, *, limit=100, check=None, before=None, after=None, around=None):
  1285. """|coro|
  1286.  
  1287. Purges a list of messages that meet the criteria given by the predicate
  1288. ``check``. If a ``check`` is not provided then all messages are deleted
  1289. without discrimination.
  1290.  
  1291. You must have Manage Messages permission to delete messages even if they
  1292. are your own. The Read Message History permission is also needed to
  1293. retrieve message history.
  1294.  
  1295. Usable only by bot accounts.
  1296.  
  1297. Parameters
  1298. -----------
  1299. channel : :class:`Channel`
  1300. The channel to purge from.
  1301. limit : int
  1302. The number of messages to search through. This is not the number
  1303. of messages that will be deleted, though it can be.
  1304. check : predicate
  1305. The function used to check if a message should be deleted.
  1306. It must take a :class:`Message` as its sole parameter.
  1307. before : :class:`Message` or `datetime`
  1308. The message or date before which all deleted messages must be.
  1309. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1310. after : :class:`Message` or `datetime`
  1311. The message or date after which all deleted messages must be.
  1312. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1313. around : :class:`Message` or `datetime`
  1314. The message or date around which all deleted messages must be.
  1315. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1316.  
  1317. Raises
  1318. -------
  1319. Forbidden
  1320. You do not have proper permissions to do the actions required or
  1321. you're not using a bot account.
  1322. HTTPException
  1323. Purging the messages failed.
  1324.  
  1325. Examples
  1326. ---------
  1327.  
  1328. Deleting bot's messages ::
  1329.  
  1330. def is_me(m):
  1331. return m.author == client.user
  1332.  
  1333. deleted = await client.purge_from(channel, limit=100, check=is_me)
  1334. await client.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))
  1335.  
  1336. Returns
  1337. --------
  1338. list
  1339. The list of messages that were deleted.
  1340. """
  1341.  
  1342. if check is None:
  1343. check = lambda m: True
  1344.  
  1345. if isinstance(before, datetime.datetime):
  1346. before = Object(utils.time_snowflake(before, high=False))
  1347. if isinstance(after, datetime.datetime):
  1348. after = Object(utils.time_snowflake(after, high=True))
  1349. if isinstance(around, datetime.datetime):
  1350. around = Object(utils.time_snowflake(around, high=True))
  1351.  
  1352. iterator = LogsFromIterator(self, channel, limit, before=before, after=after, around=around)
  1353. ret = []
  1354. count = 0
  1355.  
  1356. while True:
  1357. try:
  1358. msg = yield from iterator.iterate()
  1359. except asyncio.QueueEmpty:
  1360. # no more messages to poll
  1361. if count >= 2:
  1362. # more than 2 messages -> bulk delete
  1363. to_delete = ret[-count:]
  1364. yield from self.delete_messages(to_delete)
  1365. elif count == 1:
  1366. # delete a single message
  1367. yield from self.delete_message(ret[-1])
  1368.  
  1369. return ret
  1370. else:
  1371. if count == 100:
  1372. # we've reached a full 'queue'
  1373. to_delete = ret[-100:]
  1374. yield from self.delete_messages(to_delete)
  1375. count = 0
  1376. yield from asyncio.sleep(1, loop=self.loop)
  1377.  
  1378. if check(msg):
  1379. count += 1
  1380. ret.append(msg)
  1381.  
  1382. @asyncio.coroutine
  1383. def edit_message(self, message, new_content=None, *, embed=None):
  1384. """|coro|
  1385.  
  1386. Edits a :class:`Message` with the new message content.
  1387.  
  1388. The new_content must be able to be transformed into a string via ``str(new_content)``.
  1389.  
  1390. If the ``new_content`` is not provided, then ``embed`` must be provided, which must
  1391. be of type :class:`Embed`.
  1392.  
  1393. The :class:`Message` object is not directly modified afterwards until the
  1394. corresponding WebSocket event is received.
  1395.  
  1396. Parameters
  1397. -----------
  1398. message : :class:`Message`
  1399. The message to edit.
  1400. new_content
  1401. The new content to replace the message with.
  1402. embed: :class:`Embed`
  1403. The new embed to replace the original embed with.
  1404.  
  1405. Raises
  1406. -------
  1407. HTTPException
  1408. Editing the message failed.
  1409.  
  1410. Returns
  1411. --------
  1412. :class:`Message`
  1413. The new edited message.
  1414. """
  1415.  
  1416. channel = message.channel
  1417. content = str(new_content) if new_content else None
  1418. embed = embed.to_dict() if embed else None
  1419. guild_id = channel.server.id if not getattr(channel, 'is_private', True) else None
  1420. data = yield from self.http.edit_message(message.id, channel.id, content, guild_id=guild_id, embed=embed)
  1421. return self.connection._create_message(channel=channel, **data)
  1422.  
  1423. @asyncio.coroutine
  1424. def get_message(self, channel, id):
  1425. """|coro|
  1426.  
  1427. Retrieves a single :class:`Message` from a :class:`Channel`.
  1428.  
  1429. This can only be used by bot accounts.
  1430.  
  1431. Parameters
  1432. ------------
  1433. channel: :class:`Channel` or :class:`PrivateChannel`
  1434. The text channel to retrieve the message from.
  1435. id: str
  1436. The message ID to look for.
  1437.  
  1438. Returns
  1439. --------
  1440. :class:`Message`
  1441. The message asked for.
  1442.  
  1443. Raises
  1444. --------
  1445. NotFound
  1446. The specified channel or message was not found.
  1447. Forbidden
  1448. You do not have the permissions required to get a message.
  1449. HTTPException
  1450. Retrieving the message failed.
  1451. """
  1452.  
  1453. data = yield from self.http.get_message(channel.id, id)
  1454. return self.connection._create_message(channel=channel, **data)
  1455.  
  1456. @asyncio.coroutine
  1457. def pin_message(self, message):
  1458. """|coro|
  1459.  
  1460. Pins a message. You must have Manage Messages permissions
  1461. to do this in a non-private channel context.
  1462.  
  1463. Parameters
  1464. -----------
  1465. message: :class:`Message`
  1466. The message to pin.
  1467.  
  1468. Raises
  1469. -------
  1470. Forbidden
  1471. You do not have permissions to pin the message.
  1472. NotFound
  1473. The message or channel was not found.
  1474. HTTPException
  1475. Pinning the message failed, probably due to the channel
  1476. having more than 50 pinned messages.
  1477. """
  1478. yield from self.http.pin_message(message.channel.id, message.id)
  1479.  
  1480. @asyncio.coroutine
  1481. def unpin_message(self, message):
  1482. """|coro|
  1483.  
  1484. Unpins a message. You must have Manage Messages permissions
  1485. to do this in a non-private channel context.
  1486.  
  1487. Parameters
  1488. -----------
  1489. message: :class:`Message`
  1490. The message to unpin.
  1491.  
  1492. Raises
  1493. -------
  1494. Forbidden
  1495. You do not have permissions to unpin the message.
  1496. NotFound
  1497. The message or channel was not found.
  1498. HTTPException
  1499. Unpinning the message failed.
  1500. """
  1501. yield from self.http.unpin_message(message.channel.id, message.id)
  1502.  
  1503. @asyncio.coroutine
  1504. def pins_from(self, channel):
  1505. """|coro|
  1506.  
  1507. Returns a list of :class:`Message` that are currently pinned for
  1508. the specified :class:`Channel` or :class:`PrivateChannel`.
  1509.  
  1510. Parameters
  1511. -----------
  1512. channel: :class:`Channel` or :class:`PrivateChannel`
  1513. The channel to look through pins for.
  1514.  
  1515. Raises
  1516. -------
  1517. NotFound
  1518. The channel was not found.
  1519. HTTPException
  1520. Retrieving the pinned messages failed.
  1521. """
  1522.  
  1523. data = yield from self.http.pins_from(channel.id)
  1524. return [self.connection._create_message(channel=channel, **m) for m in data]
  1525.  
  1526. def _logs_from(self, channel, limit=100, before=None, after=None, around=None):
  1527. """|coro|
  1528.  
  1529. This coroutine returns a generator that obtains logs from a specified channel.
  1530.  
  1531. Parameters
  1532. -----------
  1533. channel : :class:`Channel` or :class:`PrivateChannel`
  1534. The channel to obtain the logs from.
  1535. limit : int
  1536. The number of messages to retrieve.
  1537. before : :class:`Message` or `datetime`
  1538. The message or date before which all returned messages must be.
  1539. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1540. after : :class:`Message` or `datetime`
  1541. The message or date after which all returned messages must be.
  1542. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1543. around : :class:`Message` or `datetime`
  1544. The message or date around which all returned messages must be.
  1545. If a date is provided it must be a timezone-naive datetime representing UTC time.
  1546.  
  1547. Raises
  1548. ------
  1549. Forbidden
  1550. You do not have permissions to get channel logs.
  1551. NotFound
  1552. The channel you are requesting for doesn't exist.
  1553. HTTPException
  1554. The request to get logs failed.
  1555.  
  1556. Yields
  1557. -------
  1558. :class:`Message`
  1559. The message with the message data parsed.
  1560.  
  1561. Examples
  1562. ---------
  1563.  
  1564. Basic logging: ::
  1565.  
  1566. logs = yield from client.logs_from(channel)
  1567. for message in logs:
  1568. if message.content.startswith('!hello'):
  1569. if message.author == client.user:
  1570. yield from client.edit_message(message, 'goodbye')
  1571.  
  1572. Python 3.5 Usage ::
  1573.  
  1574. counter = 0
  1575. async for message in client.logs_from(channel, limit=500):
  1576. if message.author == client.user:
  1577. counter += 1
  1578. """
  1579. before = getattr(before, 'id', None)
  1580. after = getattr(after, 'id', None)
  1581. around = getattr(around, 'id', None)
  1582.  
  1583. return self.http.logs_from(channel.id, limit, before=before, after=after, around=around)
  1584.  
  1585. if PY35:
  1586. def logs_from(self, channel, limit=100, *, before=None, after=None, around=None, reverse=False):
  1587. if isinstance(before, datetime.datetime):
  1588. before = Object(utils.time_snowflake(before, high=False))
  1589. if isinstance(after, datetime.datetime):
  1590. after = Object(utils.time_snowflake(after, high=True))
  1591. if isinstance(around, datetime.datetime):
  1592. around = Object(utils.time_snowflake(around))
  1593.  
  1594. return LogsFromIterator(self, channel, limit, before=before, after=after, around=around, reverse=reverse)
  1595. else:
  1596. @asyncio.coroutine
  1597. def logs_from(self, channel, limit=100, *, before=None, after=None):
  1598. if isinstance(before, datetime.datetime):
  1599. before = Object(utils.time_snowflake(before, high=False))
  1600. if isinstance(after, datetime.datetime):
  1601. after = Object(utils.time_snowflake(after, high=True))
  1602.  
  1603. def generator(data):
  1604. for message in data:
  1605. yield self.connection._create_message(channel=channel, **message)
  1606.  
  1607. result = []
  1608. while limit > 0:
  1609. retrieve = limit if limit <= 100 else 100
  1610. data = yield from self._logs_from(channel, retrieve, before, after)
  1611. if len(data):
  1612. limit -= retrieve
  1613. result.extend(data)
  1614. before = Object(id=data[-1]['id'])
  1615. else:
  1616. break
  1617.  
  1618. return generator(result)
  1619.  
  1620. logs_from.__doc__ = _logs_from.__doc__
  1621.  
  1622. # Member management
  1623.  
  1624. @asyncio.coroutine
  1625. def request_offline_members(self, server):
  1626. """|coro|
  1627.  
  1628. Requests previously offline members from the server to be filled up
  1629. into the :attr:`Server.members` cache. This function is usually not
  1630. called.
  1631.  
  1632. When the client logs on and connects to the websocket, Discord does
  1633. not provide the library with offline members if the number of members
  1634. in the server is larger than 250. You can check if a server is large
  1635. if :attr:`Server.large` is ``True``.
  1636.  
  1637. Parameters
  1638. -----------
  1639. server : :class:`Server` or iterable
  1640. The server to request offline members for. If this parameter is a
  1641. iterable then it is interpreted as an iterator of servers to
  1642. request offline members for.
  1643. """
  1644.  
  1645. if hasattr(server, 'id'):
  1646. guild_id = server.id
  1647. else:
  1648. guild_id = [s.id for s in server]
  1649.  
  1650. payload = {
  1651. 'op': 8,
  1652. 'd': {
  1653. 'guild_id': guild_id,
  1654. 'query': '',
  1655. 'limit': 0
  1656. }
  1657. }
  1658.  
  1659. yield from self.ws.send_as_json(payload)
  1660.  
  1661. @asyncio.coroutine
  1662. def kick(self, member):
  1663. """|coro|
  1664.  
  1665. Kicks a :class:`Member` from the server they belong to.
  1666.  
  1667. Warning
  1668. --------
  1669. This function kicks the :class:`Member` based on the server it
  1670. belongs to, which is accessed via :attr:`Member.server`. So you
  1671. must have the proper permissions in that server.
  1672.  
  1673. Parameters
  1674. -----------
  1675. member : :class:`Member`
  1676. The member to kick from their server.
  1677.  
  1678. Raises
  1679. -------
  1680. Forbidden
  1681. You do not have the proper permissions to kick.
  1682. HTTPException
  1683. Kicking failed.
  1684. """
  1685. yield from self.http.kick(member.id, member.server.id)
  1686.  
  1687. @asyncio.coroutine
  1688. def ban(self, member, delete_message_days=1):
  1689. """|coro|
  1690.  
  1691. Bans a :class:`Member` from the server they belong to.
  1692.  
  1693. Warning
  1694. --------
  1695. This function bans the :class:`Member` based on the server it
  1696. belongs to, which is accessed via :attr:`Member.server`. So you
  1697. must have the proper permissions in that server.
  1698.  
  1699. Parameters
  1700. -----------
  1701. member : :class:`Member`
  1702. The member to ban from their server.
  1703. delete_message_days : int
  1704. The number of days worth of messages to delete from the user
  1705. in the server. The minimum is 0 and the maximum is 7.
  1706.  
  1707. Raises
  1708. -------
  1709. Forbidden
  1710. You do not have the proper permissions to ban.
  1711. HTTPException
  1712. Banning failed.
  1713. """
  1714. yield from self.http.ban(member.id, member.server.id, delete_message_days)
  1715.  
  1716. @asyncio.coroutine
  1717. def unban(self, server, user):
  1718. """|coro|
  1719.  
  1720. Unbans a :class:`User` from the server they are banned from.
  1721.  
  1722. Parameters
  1723. -----------
  1724. server : :class:`Server`
  1725. The server to unban the user from.
  1726. user : :class:`User`
  1727. The user to unban.
  1728.  
  1729. Raises
  1730. -------
  1731. Forbidden
  1732. You do not have the proper permissions to unban.
  1733. HTTPException
  1734. Unbanning failed.
  1735. """
  1736. yield from self.http.unban(user.id, server.id)
  1737.  
  1738. @asyncio.coroutine
  1739. def server_voice_state(self, member, *, mute=None, deafen=None):
  1740. """|coro|
  1741.  
  1742. Server mutes or deafens a specific :class:`Member`.
  1743.  
  1744. Warning
  1745. --------
  1746. This function mutes or un-deafens the :class:`Member` based on the
  1747. server it belongs to, which is accessed via :attr:`Member.server`.
  1748. So you must have the proper permissions in that server.
  1749.  
  1750. Parameters
  1751. -----------
  1752. member : :class:`Member`
  1753. The member to unban from their server.
  1754. mute: Optional[bool]
  1755. Indicates if the member should be server muted or un-muted.
  1756. deafen: Optional[bool]
  1757. Indicates if the member should be server deafened or un-deafened.
  1758.  
  1759. Raises
  1760. -------
  1761. Forbidden
  1762. You do not have the proper permissions to deafen or mute.
  1763. HTTPException
  1764. The operation failed.
  1765. """
  1766. yield from self.http.server_voice_state(member.id, member.server.id, mute=mute, deafen=deafen)
  1767.  
  1768. @asyncio.coroutine
  1769. def edit_profile(self, password=None, **fields):
  1770. """|coro|
  1771.  
  1772. Edits the current profile of the client.
  1773.  
  1774. If a bot account is used then the password field is optional,
  1775. otherwise it is required.
  1776.  
  1777. The :attr:`Client.user` object is not modified directly afterwards until the
  1778. corresponding WebSocket event is received.
  1779.  
  1780. Note
  1781. -----
  1782. To upload an avatar, a *bytes-like object* must be passed in that
  1783. represents the image being uploaded. If this is done through a file
  1784. then the file must be opened via ``open('some_filename', 'rb')`` and
  1785. the *bytes-like object* is given through the use of ``fp.read()``.
  1786.  
  1787. The only image formats supported for uploading is JPEG and PNG.
  1788.  
  1789. Parameters
  1790. -----------
  1791. password : str
  1792. The current password for the client's account. Not used
  1793. for bot accounts.
  1794. new_password : str
  1795. The new password you wish to change to.
  1796. email : str
  1797. The new email you wish to change to.
  1798. username :str
  1799. The new username you wish to change to.
  1800. avatar : bytes
  1801. A *bytes-like object* representing the image to upload.
  1802. Could be ``None`` to denote no avatar.
  1803.  
  1804. Raises
  1805. ------
  1806. HTTPException
  1807. Editing your profile failed.
  1808. InvalidArgument
  1809. Wrong image format passed for ``avatar``.
  1810. ClientException
  1811. Password is required for non-bot accounts.
  1812. """
  1813.  
  1814. try:
  1815. avatar_bytes = fields['avatar']
  1816. except KeyError:
  1817. avatar = self.user.avatar
  1818. else:
  1819. if avatar_bytes is not None:
  1820. avatar = utils._bytes_to_base64_data(avatar_bytes)
  1821. else:
  1822. avatar = None
  1823.  
  1824. not_bot_account = not self.user.bot
  1825. if not_bot_account and password is None:
  1826. raise ClientException('Password is required for non-bot accounts.')
  1827.  
  1828. args = {
  1829. 'password': password,
  1830. 'username': fields.get('username', self.user.name),
  1831. 'avatar': avatar
  1832. }
  1833.  
  1834. if not_bot_account:
  1835. args['email'] = fields.get('email', self.email)
  1836.  
  1837. if 'new_password' in fields:
  1838. args['new_password'] = fields['new_password']
  1839.  
  1840. data = yield from self.http.edit_profile(**args)
  1841. if not_bot_account:
  1842. self.email = data['email']
  1843. if 'token' in data:
  1844. self.http._token(data['token'], bot=False)
  1845.  
  1846. if self.cache_auth:
  1847. self._update_cache(self.email, password)
  1848.  
  1849. @asyncio.coroutine
  1850. @utils.deprecated('change_presence')
  1851. def change_status(self, game=None, idle=False):
  1852. """|coro|
  1853.  
  1854. Changes the client's status.
  1855.  
  1856. The game parameter is a Game object (not a string) that represents
  1857. a game being played currently.
  1858.  
  1859. The idle parameter is a boolean parameter that indicates whether the
  1860. client should go idle or not.
  1861.  
  1862. .. deprecated:: v0.13.0
  1863. Use :meth:`change_presence` instead.
  1864.  
  1865. Parameters
  1866. ----------
  1867. game : Optional[:class:`Game`]
  1868. The game being played. None if no game is being played.
  1869. idle : bool
  1870. Indicates if the client should go idle.
  1871.  
  1872. Raises
  1873. ------
  1874. InvalidArgument
  1875. If the ``game`` parameter is not :class:`Game` or None.
  1876. """
  1877. yield from self.ws.change_presence(game=game, idle=idle)
  1878.  
  1879. @asyncio.coroutine
  1880. def change_presence(self, *, game=None, status=None, afk=False):
  1881. """|coro|
  1882.  
  1883. Changes the client's presence.
  1884.  
  1885. The game parameter is a Game object (not a string) that represents
  1886. a game being played currently.
  1887.  
  1888. Parameters
  1889. ----------
  1890. game: Optional[:class:`Game`]
  1891. The game being played. None if no game is being played.
  1892. status: Optional[:class:`Status`]
  1893. Indicates what status to change to. If None, then
  1894. :attr:`Status.online` is used.
  1895. afk: bool
  1896. Indicates if you are going AFK. This allows the discord
  1897. client to know how to handle push notifications better
  1898. for you in case you are actually idle and not lying.
  1899.  
  1900. Raises
  1901. ------
  1902. InvalidArgument
  1903. If the ``game`` parameter is not :class:`Game` or None.
  1904. """
  1905.  
  1906. if status is None:
  1907. status = 'online'
  1908. elif status is Status.offline:
  1909. status = 'invisible'
  1910. else:
  1911. status = str(status)
  1912.  
  1913. yield from self.ws.change_presence(game=game, status=status, afk=afk)
  1914.  
  1915. @asyncio.coroutine
  1916. def change_nickname(self, member, nickname):
  1917. """|coro|
  1918.  
  1919. Changes a member's nickname.
  1920.  
  1921. You must have the proper permissions to change someone's
  1922. (or your own) nickname.
  1923.  
  1924. Parameters
  1925. ----------
  1926. member : :class:`Member`
  1927. The member to change the nickname for.
  1928. nickname : Optional[str]
  1929. The nickname to change it to. ``None`` to remove
  1930. the nickname.
  1931.  
  1932. Raises
  1933. ------
  1934. Forbidden
  1935. You do not have permissions to change the nickname.
  1936. HTTPException
  1937. Changing the nickname failed.
  1938. """
  1939.  
  1940. nickname = nickname if nickname else ''
  1941.  
  1942. if member == self.user:
  1943. yield from self.http.change_my_nickname(member.server.id, nickname)
  1944. else:
  1945. yield from self.http.change_nickname(member.server.id, member.id, nickname)
  1946.  
  1947. # Channel management
  1948.  
  1949. @asyncio.coroutine
  1950. def edit_channel(self, channel, **options):
  1951. """|coro|
  1952.  
  1953. Edits a :class:`Channel`.
  1954.  
  1955. You must have the proper permissions to edit the channel.
  1956.  
  1957. To move the channel's position use :meth:`move_channel` instead.
  1958.  
  1959. The :class:`Channel` object is not directly modified afterwards until the
  1960. corresponding WebSocket event is received.
  1961.  
  1962. Parameters
  1963. ----------
  1964. channel : :class:`Channel`
  1965. The channel to update.
  1966. name : str
  1967. The new channel name.
  1968. topic : str
  1969. The new channel's topic.
  1970. bitrate : int
  1971. The new channel's bitrate. Voice only.
  1972. user_limit : int
  1973. The new channel's user limit. Voice only.
  1974.  
  1975. Raises
  1976. ------
  1977. Forbidden
  1978. You do not have permissions to edit the channel.
  1979. HTTPException
  1980. Editing the channel failed.
  1981. """
  1982.  
  1983. keys = ('name', 'topic', 'position')
  1984. for key in keys:
  1985. if key not in options:
  1986. options[key] = getattr(channel, key)
  1987.  
  1988. yield from self.http.edit_channel(channel.id, **options)
  1989.  
  1990. @asyncio.coroutine
  1991. def move_channel(self, channel, position):
  1992. """|coro|
  1993.  
  1994. Moves the specified :class:`Channel` to the given position in the GUI.
  1995. Note that voice channels and text channels have different position values.
  1996.  
  1997. The :class:`Channel` object is not directly modified afterwards until the
  1998. corresponding WebSocket event is received.
  1999.  
  2000. .. warning::
  2001.  
  2002. :class:`Object` instances do not work with this function.
  2003.  
  2004. Parameters
  2005. -----------
  2006. channel : :class:`Channel`
  2007. The channel to change positions of.
  2008. position : int
  2009. The position to insert the channel to.
  2010.  
  2011. Raises
  2012. -------
  2013. InvalidArgument
  2014. If position is less than 0 or greater than the number of channels.
  2015. Forbidden
  2016. You do not have permissions to change channel order.
  2017. HTTPException
  2018. If moving the channel failed, or you are of too low rank to move the channel.
  2019. """
  2020.  
  2021. if position < 0:
  2022. raise InvalidArgument('Channel position cannot be less than 0.')
  2023.  
  2024. url = '{0}/{1.server.id}/channels'.format(self.http.GUILDS, channel)
  2025. channels = [c for c in channel.server.channels if c.type is channel.type]
  2026.  
  2027. if position >= len(channels):
  2028. raise InvalidArgument('Channel position cannot be greater than {}'.format(len(channels) - 1))
  2029.  
  2030. channels.sort(key=lambda c: c.position)
  2031.  
  2032. try:
  2033. # remove ourselves from the channel list
  2034. channels.remove(channel)
  2035. except ValueError:
  2036. # not there somehow lol
  2037. return
  2038. else:
  2039. # add ourselves at our designated position
  2040. channels.insert(position, channel)
  2041.  
  2042. payload = [{'id': c.id, 'position': index } for index, c in enumerate(channels)]
  2043. yield from self.http.patch(url, json=payload, bucket='move_channel')
  2044.  
  2045. @asyncio.coroutine
  2046. def create_channel(self, server, name, *overwrites, type=None):
  2047. """|coro|
  2048.  
  2049. Creates a :class:`Channel` in the specified :class:`Server`.
  2050.  
  2051. Note that you need the proper permissions to create the channel.
  2052.  
  2053. The ``overwrites`` argument list can be used to create a 'secret'
  2054. channel upon creation. A namedtuple of :class:`ChannelPermissions`
  2055. is exposed to create a channel-specific permission overwrite in a more
  2056. self-documenting matter. You can also use a regular tuple of ``(target, overwrite)``
  2057. where the ``overwrite`` expected has to be of type :class:`PermissionOverwrite`.
  2058.  
  2059. Examples
  2060. ----------
  2061.  
  2062. Creating a voice channel:
  2063.  
  2064. .. code-block:: python
  2065.  
  2066. await client.create_channel(server, 'Voice', type=discord.ChannelType.voice)
  2067.  
  2068. Creating a 'secret' text channel:
  2069.  
  2070. .. code-block:: python
  2071.  
  2072. everyone_perms = discord.PermissionOverwrite(read_messages=False)
  2073. my_perms = discord.PermissionOverwrite(read_messages=True)
  2074.  
  2075. everyone = discord.ChannelPermissions(target=server.default_role, overwrite=everyone_perms)
  2076. mine = discord.ChannelPermissions(target=server.me, overwrite=my_perms)
  2077. await client.create_channel(server, 'secret', everyone, mine)
  2078.  
  2079. Or in a more 'compact' way:
  2080.  
  2081. .. code-block:: python
  2082.  
  2083. everyone = discord.PermissionOverwrite(read_messages=False)
  2084. mine = discord.PermissionOverwrite(read_messages=True)
  2085. await client.create_channel(server, 'secret', (server.default_role, everyone), (server.me, mine))
  2086.  
  2087. Parameters
  2088. -----------
  2089. server : :class:`Server`
  2090. The server to create the channel in.
  2091. name : str
  2092. The channel's name.
  2093. type : :class:`ChannelType`
  2094. The type of channel to create. Defaults to :attr:`ChannelType.text`.
  2095. overwrites:
  2096. An argument list of channel specific overwrites to apply on the channel on
  2097. creation. Useful for creating 'secret' channels.
  2098.  
  2099. Raises
  2100. -------
  2101. Forbidden
  2102. You do not have the proper permissions to create the channel.
  2103. NotFound
  2104. The server specified was not found.
  2105. HTTPException
  2106. Creating the channel failed.
  2107. InvalidArgument
  2108. The permission overwrite array is not in proper form.
  2109.  
  2110. Returns
  2111. -------
  2112. :class:`Channel`
  2113. The channel that was just created. This channel is
  2114. different than the one that will be added in cache.
  2115. """
  2116.  
  2117. if type is None:
  2118. type = ChannelType.text
  2119.  
  2120. perms = []
  2121. for overwrite in overwrites:
  2122. target = overwrite[0]
  2123. perm = overwrite[1]
  2124. if not isinstance(perm, PermissionOverwrite):
  2125. raise InvalidArgument('Expected PermissionOverwrite received {0.__name__}'.format(type(perm)))
  2126.  
  2127. allow, deny = perm.pair()
  2128. payload = {
  2129. 'allow': allow.value,
  2130. 'deny': deny.value,
  2131. 'id': target.id
  2132. }
  2133.  
  2134. if isinstance(target, User):
  2135. payload['type'] = 'member'
  2136. elif isinstance(target, Role):
  2137. payload['type'] = 'role'
  2138. else:
  2139. raise InvalidArgument('Expected Role, User, or Member target, received {0.__name__}'.format(type(target)))
  2140.  
  2141. perms.append(payload)
  2142.  
  2143. data = yield from self.http.create_channel(server.id, name, str(type), permission_overwrites=perms)
  2144. channel = Channel(server=server, **data)
  2145. return channel
  2146.  
  2147. @asyncio.coroutine
  2148. def delete_channel(self, channel):
  2149. """|coro|
  2150.  
  2151. Deletes a :class:`Channel`.
  2152.  
  2153. In order to delete the channel, the client must have the proper permissions
  2154. in the server the channel belongs to.
  2155.  
  2156. Parameters
  2157. ------------
  2158. channel : :class:`Channel`
  2159. The channel to delete.
  2160.  
  2161. Raises
  2162. -------
  2163. Forbidden
  2164. You do not have proper permissions to delete the channel.
  2165. NotFound
  2166. The specified channel was not found.
  2167. HTTPException
  2168. Deleting the channel failed.
  2169. """
  2170. yield from self.http.delete_channel(channel.id)
  2171.  
  2172. # Server management
  2173.  
  2174. @asyncio.coroutine
  2175. def leave_server(self, server):
  2176. """|coro|
  2177.  
  2178. Leaves a :class:`Server`.
  2179.  
  2180. Note
  2181. --------
  2182. You cannot leave the server that you own, you must delete it instead
  2183. via :meth:`delete_server`.
  2184.  
  2185. Parameters
  2186. ----------
  2187. server : :class:`Server`
  2188. The server to leave.
  2189.  
  2190. Raises
  2191. --------
  2192. HTTPException
  2193. If leaving the server failed.
  2194. """
  2195. yield from self.http.leave_server(server.id)
  2196.  
  2197. @asyncio.coroutine
  2198. def delete_server(self, server):
  2199. """|coro|
  2200.  
  2201. Deletes a :class:`Server`. You must be the server owner to delete the
  2202. server.
  2203.  
  2204. Parameters
  2205. ----------
  2206. server : :class:`Server`
  2207. The server to delete.
  2208.  
  2209. Raises
  2210. --------
  2211. HTTPException
  2212. If deleting the server failed.
  2213. Forbidden
  2214. You do not have permissions to delete the server.
  2215. """
  2216.  
  2217. yield from self.http.delete_server(server.id)
  2218.  
  2219. @asyncio.coroutine
  2220. def create_server(self, name, region=None, icon=None):
  2221. """|coro|
  2222.  
  2223. Creates a :class:`Server`.
  2224.  
  2225. Parameters
  2226. ----------
  2227. name : str
  2228. The name of the server.
  2229. region : :class:`ServerRegion`
  2230. The region for the voice communication server.
  2231. Defaults to :attr:`ServerRegion.us_west`.
  2232. icon : bytes
  2233. The *bytes-like* object representing the icon. See :meth:`edit_profile`
  2234. for more details on what is expected.
  2235.  
  2236. Raises
  2237. ------
  2238. HTTPException
  2239. Server creation failed.
  2240. InvalidArgument
  2241. Invalid icon image format given. Must be PNG or JPG.
  2242.  
  2243. Returns
  2244. -------
  2245. :class:`Server`
  2246. The server created. This is not the same server that is
  2247. added to cache.
  2248. """
  2249. if icon is not None:
  2250. icon = utils._bytes_to_base64_data(icon)
  2251.  
  2252. if region is None:
  2253. region = ServerRegion.us_west.name
  2254. else:
  2255. region = region.name
  2256.  
  2257. data = yield from self.http.create_server(name, region, icon)
  2258. return Server(**data)
  2259.  
  2260. @asyncio.coroutine
  2261. def edit_server(self, server, **fields):
  2262. """|coro|
  2263.  
  2264. Edits a :class:`Server`.
  2265.  
  2266. You must have the proper permissions to edit the server.
  2267.  
  2268. The :class:`Server` object is not directly modified afterwards until the
  2269. corresponding WebSocket event is received.
  2270.  
  2271. Parameters
  2272. ----------
  2273. server: :class:`Server`
  2274. The server to edit.
  2275. name: str
  2276. The new name of the server.
  2277. icon: bytes
  2278. A *bytes-like* object representing the icon. See :meth:`edit_profile`
  2279. for more details. Could be ``None`` to denote no icon.
  2280. splash: bytes
  2281. A *bytes-like* object representing the invite splash. See
  2282. :meth:`edit_profile` for more details. Could be ``None`` to denote
  2283. no invite splash. Only available for partnered servers with
  2284. ``INVITE_SPLASH`` feature.
  2285. region: :class:`ServerRegion`
  2286. The new region for the server's voice communication.
  2287. afk_channel: :class:`Channel`
  2288. The new channel that is the AFK channel. Could be ``None`` for no AFK channel.
  2289. afk_timeout: int
  2290. The number of seconds until someone is moved to the AFK channel.
  2291. owner: :class:`Member`
  2292. The new owner of the server to transfer ownership to. Note that you must
  2293. be owner of the server to do this.
  2294. verification_level: :class:`VerificationLevel`
  2295. The new verification level for the server.
  2296.  
  2297. Raises
  2298. -------
  2299. Forbidden
  2300. You do not have permissions to edit the server.
  2301. NotFound
  2302. The server you are trying to edit does not exist.
  2303. HTTPException
  2304. Editing the server failed.
  2305. InvalidArgument
  2306. The image format passed in to ``icon`` is invalid. It must be
  2307. PNG or JPG. This is also raised if you are not the owner of the
  2308. server and request an ownership transfer.
  2309. """
  2310.  
  2311. try:
  2312. icon_bytes = fields['icon']
  2313. except KeyError:
  2314. icon = server.icon
  2315. else:
  2316. if icon_bytes is not None:
  2317. icon = utils._bytes_to_base64_data(icon_bytes)
  2318. else:
  2319. icon = None
  2320.  
  2321. try:
  2322. splash_bytes = fields['splash']
  2323. except KeyError:
  2324. splash = server.splash
  2325. else:
  2326. if splash_bytes is not None:
  2327. splash = utils._bytes_to_base64_data(splash_bytes)
  2328. else:
  2329. splash = None
  2330.  
  2331. fields['icon'] = icon
  2332. fields['splash'] = splash
  2333. if 'afk_channel' in fields:
  2334. fields['afk_channel_id'] = fields['afk_channel'].id
  2335.  
  2336. if 'owner' in fields:
  2337. if server.owner != server.me:
  2338. raise InvalidArgument('To transfer ownership you must be the owner of the server.')
  2339.  
  2340. fields['owner_id'] = fields['owner'].id
  2341.  
  2342. if 'region' in fields:
  2343. fields['region'] = str(fields['region'])
  2344.  
  2345. level = fields.get('verification_level', server.verification_level)
  2346. if not isinstance(level, VerificationLevel):
  2347. raise InvalidArgument('verification_level field must of type VerificationLevel')
  2348.  
  2349. fields['verification_level'] = level.value
  2350. yield from self.http.edit_server(server.id, **fields)
  2351.  
  2352. @asyncio.coroutine
  2353. def get_bans(self, server):
  2354. """|coro|
  2355.  
  2356. Retrieves all the :class:`User` s that are banned from the specified
  2357. server.
  2358.  
  2359. You must have proper permissions to get this information.
  2360.  
  2361. Parameters
  2362. ----------
  2363. server : :class:`Server`
  2364. The server to get ban information from.
  2365.  
  2366. Raises
  2367. -------
  2368. Forbidden
  2369. You do not have proper permissions to get the information.
  2370. HTTPException
  2371. An error occurred while fetching the information.
  2372.  
  2373. Returns
  2374. --------
  2375. list
  2376. A list of :class:`User` that have been banned.
  2377. """
  2378.  
  2379. data = yield from self.http.get_bans(server.id)
  2380. return [User(**user['user']) for user in data]
  2381.  
  2382. @asyncio.coroutine
  2383. def prune_members(self, server, *, days):
  2384. """|coro|
  2385.  
  2386. Prunes a :class:`Server` from its inactive members.
  2387.  
  2388. The inactive members are denoted if they have not logged on in
  2389. ``days`` number of days and they have no roles.
  2390.  
  2391. You must have the "Kick Members" permission to use this.
  2392.  
  2393. To check how many members you would prune without actually pruning,
  2394. see the :meth:`estimate_pruned_members` function.
  2395.  
  2396. Parameters
  2397. -----------
  2398. server: :class:`Server`
  2399. The server to prune from.
  2400. days: int
  2401. The number of days before counting as inactive.
  2402.  
  2403. Raises
  2404. -------
  2405. Forbidden
  2406. You do not have permissions to prune members.
  2407. HTTPException
  2408. An error occurred while pruning members.
  2409. InvalidArgument
  2410. An integer was not passed for ``days``.
  2411.  
  2412. Returns
  2413. ---------
  2414. int
  2415. The number of members pruned.
  2416. """
  2417.  
  2418. if not isinstance(days, int):
  2419. raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
  2420.  
  2421. data = yield from self.http.prune_members(server.id, days)
  2422. return data['pruned']
  2423.  
  2424. @asyncio.coroutine
  2425. def estimate_pruned_members(self, server, *, days):
  2426. """|coro|
  2427.  
  2428. Similar to :meth:`prune_members` except instead of actually
  2429. pruning members, it returns how many members it would prune
  2430. from the server had it been called.
  2431.  
  2432. Parameters
  2433. -----------
  2434. server: :class:`Server`
  2435. The server to estimate a prune from.
  2436. days: int
  2437. The number of days before counting as inactive.
  2438.  
  2439. Raises
  2440. -------
  2441. Forbidden
  2442. You do not have permissions to prune members.
  2443. HTTPException
  2444. An error occurred while fetching the prune members estimate.
  2445. InvalidArgument
  2446. An integer was not passed for ``days``.
  2447.  
  2448. Returns
  2449. ---------
  2450. int
  2451. The number of members estimated to be pruned.
  2452. """
  2453.  
  2454. if not isinstance(days, int):
  2455. raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days))
  2456.  
  2457. data = yield from self.http.estimate_pruned_members(server.id, days)
  2458. return data['pruned']
  2459.  
  2460. @asyncio.coroutine
  2461. def create_custom_emoji(self, server, *, name, image):
  2462. """|coro|
  2463.  
  2464. Creates a custom :class:`Emoji` for a :class:`Server`.
  2465.  
  2466. This endpoint is only allowed for user bots or white listed
  2467. bots. If this is done by a user bot then this is a local
  2468. emoji that can only be used inside that server.
  2469.  
  2470. There is currently a limit of 50 local emotes per server.
  2471.  
  2472. Parameters
  2473. -----------
  2474. server: :class:`Server`
  2475. The server to add the emoji to.
  2476. name: str
  2477. The emoji name. Must be at least 2 characters.
  2478. image: bytes
  2479. The *bytes-like* object representing the image data to use.
  2480. Only JPG and PNG images are supported.
  2481.  
  2482. Returns
  2483. --------
  2484. :class:`Emoji`
  2485. The created emoji.
  2486.  
  2487. Raises
  2488. -------
  2489. Forbidden
  2490. You are not allowed to create emojis.
  2491. HTTPException
  2492. An error occurred creating an emoji.
  2493. """
  2494.  
  2495. img = utils._bytes_to_base64_data(image)
  2496. data = yield from self.http.create_custom_emoji(server.id, name, img)
  2497. return Emoji(server=server, **data)
  2498.  
  2499. @asyncio.coroutine
  2500. def delete_custom_emoji(self, emoji):
  2501. """|coro|
  2502.  
  2503. Deletes a custom :class:`Emoji` from a :class:`Server`.
  2504.  
  2505. This follows the same rules as :meth:`create_custom_emoji`.
  2506.  
  2507. Parameters
  2508. -----------
  2509. emoji: :class:`Emoji`
  2510. The emoji to delete.
  2511.  
  2512. Raises
  2513. -------
  2514. Forbidden
  2515. You are not allowed to delete emojis.
  2516. HTTPException
  2517. An error occurred deleting the emoji.
  2518. """
  2519.  
  2520. yield from self.http.delete_custom_emoji(emoji.server.id, emoji.id)
  2521.  
  2522. @asyncio.coroutine
  2523. def edit_custom_emoji(self, emoji, *, name):
  2524. """|coro|
  2525.  
  2526. Edits a :class:`Emoji`.
  2527.  
  2528. Parameters
  2529. -----------
  2530. emoji: :class:`Emoji`
  2531. The emoji to edit.
  2532. name: str
  2533. The new emoji name.
  2534.  
  2535. Raises
  2536. -------
  2537. Forbidden
  2538. You are not allowed to edit emojis.
  2539. HTTPException
  2540. An error occurred editing the emoji.
  2541. """
  2542.  
  2543. yield from self.http.edit_custom_emoji(emoji.server.id, emoji.id, name=name)
  2544.  
  2545.  
  2546. # Invite management
  2547.  
  2548. def _fill_invite_data(self, data):
  2549. server = self.connection._get_server(data['guild']['id'])
  2550. if server is not None:
  2551. ch_id = data['channel']['id']
  2552. channel = server.get_channel(ch_id)
  2553. else:
  2554. server = Object(id=data['guild']['id'])
  2555. server.name = data['guild']['name']
  2556. channel = Object(id=data['channel']['id'])
  2557. channel.name = data['channel']['name']
  2558. data['server'] = server
  2559. data['channel'] = channel
  2560.  
  2561. @asyncio.coroutine
  2562. def create_invite(self, destination, **options):
  2563. """|coro|
  2564.  
  2565. Creates an invite for the destination which could be either a
  2566. :class:`Server` or :class:`Channel`.
  2567.  
  2568. Parameters
  2569. ------------
  2570. destination
  2571. The :class:`Server` or :class:`Channel` to create the invite to.
  2572. max_age : int
  2573. How long the invite should last. If it's 0 then the invite
  2574. doesn't expire. Defaults to 0.
  2575. max_uses : int
  2576. How many uses the invite could be used for. If it's 0 then there
  2577. are unlimited uses. Defaults to 0.
  2578. temporary : bool
  2579. Denotes that the invite grants temporary membership
  2580. (i.e. they get kicked after they disconnect). Defaults to False.
  2581. xkcd : bool
  2582. Indicates if the invite URL is human readable. Defaults to False.
  2583.  
  2584. Raises
  2585. -------
  2586. HTTPException
  2587. Invite creation failed.
  2588.  
  2589. Returns
  2590. --------
  2591. :class:`Invite`
  2592. The invite that was created.
  2593. """
  2594.  
  2595. data = yield from self.http.create_invite(destination.id, **options)
  2596. self._fill_invite_data(data)
  2597. return Invite(**data)
  2598.  
  2599. @asyncio.coroutine
  2600. def get_invite(self, url):
  2601. """|coro|
  2602.  
  2603. Gets a :class:`Invite` from a discord.gg URL or ID.
  2604.  
  2605. Note
  2606. ------
  2607. If the invite is for a server you have not joined, the server and channel
  2608. attributes of the returned invite will be :class:`Object` with the names
  2609. patched in.
  2610.  
  2611. Parameters
  2612. -----------
  2613. url : str
  2614. The discord invite ID or URL (must be a discord.gg URL).
  2615.  
  2616. Raises
  2617. -------
  2618. NotFound
  2619. The invite has expired or is invalid.
  2620. HTTPException
  2621. Getting the invite failed.
  2622.  
  2623. Returns
  2624. --------
  2625. :class:`Invite`
  2626. The invite from the URL/ID.
  2627. """
  2628.  
  2629. invite_id = self._resolve_invite(url)
  2630. data = yield from self.http.get_invite(invite_id)
  2631. self._fill_invite_data(data)
  2632. return Invite(**data)
  2633.  
  2634. @asyncio.coroutine
  2635. def invites_from(self, server):
  2636. """|coro|
  2637.  
  2638. Returns a list of all active instant invites from a :class:`Server`.
  2639.  
  2640. You must have proper permissions to get this information.
  2641.  
  2642. Parameters
  2643. ----------
  2644. server : :class:`Server`
  2645. The server to get invites from.
  2646.  
  2647. Raises
  2648. -------
  2649. Forbidden
  2650. You do not have proper permissions to get the information.
  2651. HTTPException
  2652. An error occurred while fetching the information.
  2653.  
  2654. Returns
  2655. -------
  2656. list of :class:`Invite`
  2657. The list of invites that are currently active.
  2658. """
  2659.  
  2660. data = yield from self.http.invites_from(server.id)
  2661. result = []
  2662. for invite in data:
  2663. channel = server.get_channel(invite['channel']['id'])
  2664. invite['channel'] = channel
  2665. invite['server'] = server
  2666. result.append(Invite(**invite))
  2667.  
  2668. return result
  2669.  
  2670. @asyncio.coroutine
  2671. def accept_invite(self, invite):
  2672. """|coro|
  2673.  
  2674. Accepts an :class:`Invite`, URL or ID to an invite.
  2675.  
  2676. The URL must be a discord.gg URL. e.g. "http://discord.gg/codehere".
  2677. An ID for the invite is just the "codehere" portion of the invite URL.
  2678.  
  2679. Parameters
  2680. -----------
  2681. invite
  2682. The :class:`Invite` or URL to an invite to accept.
  2683.  
  2684. Raises
  2685. -------
  2686. HTTPException
  2687. Accepting the invite failed.
  2688. NotFound
  2689. The invite is invalid or expired.
  2690. Forbidden
  2691. You are a bot user and cannot use this endpoint.
  2692. """
  2693.  
  2694. invite_id = self._resolve_invite(invite)
  2695. yield from self.http.accept_invite(invite_id)
  2696.  
  2697. @asyncio.coroutine
  2698. def delete_invite(self, invite):
  2699. """|coro|
  2700.  
  2701. Revokes an :class:`Invite`, URL, or ID to an invite.
  2702.  
  2703. The ``invite`` parameter follows the same rules as
  2704. :meth:`accept_invite`.
  2705.  
  2706. Parameters
  2707. ----------
  2708. invite
  2709. The invite to revoke.
  2710.  
  2711. Raises
  2712. -------
  2713. Forbidden
  2714. You do not have permissions to revoke invites.
  2715. NotFound
  2716. The invite is invalid or expired.
  2717. HTTPException
  2718. Revoking the invite failed.
  2719. """
  2720.  
  2721. invite_id = self._resolve_invite(invite)
  2722. yield from self.http.delete_invite(invite_id)
  2723.  
  2724. # Role management
  2725.  
  2726. @asyncio.coroutine
  2727. def move_role(self, server, role, position):
  2728. """|coro|
  2729.  
  2730. Moves the specified :class:`Role` to the given position in the :class:`Server`.
  2731.  
  2732. The :class:`Role` object is not directly modified afterwards until the
  2733. corresponding WebSocket event is received.
  2734.  
  2735. Parameters
  2736. -----------
  2737. server : :class:`Server`
  2738. The server the role belongs to.
  2739. role : :class:`Role`
  2740. The role to edit.
  2741. position : int
  2742. The position to insert the role to.
  2743.  
  2744. Raises
  2745. -------
  2746. InvalidArgument
  2747. If position is 0, or role is server.default_role
  2748. Forbidden
  2749. You do not have permissions to change role order.
  2750. HTTPException
  2751. If moving the role failed, or you are of too low rank to move the role.
  2752. """
  2753.  
  2754. if position == 0:
  2755. raise InvalidArgument("Cannot move role to position 0")
  2756.  
  2757. if role == server.default_role:
  2758. raise InvalidArgument("Cannot move default role")
  2759.  
  2760. if role.position == position:
  2761. return # Save discord the extra request.
  2762.  
  2763. url = '{0}/{1.id}/roles'.format(self.http.GUILDS, server)
  2764.  
  2765. change_range = range(min(role.position, position), max(role.position, position) + 1)
  2766.  
  2767. roles = [r.id for r in sorted(filter(lambda x: (x.position in change_range) and x != role, server.roles), key=lambda x: x.position)]
  2768.  
  2769. if role.position > position:
  2770. roles.insert(0, role.id)
  2771. else:
  2772. roles.append(role.id)
  2773.  
  2774. payload = [{"id": z[0], "position": z[1]} for z in zip(roles, change_range)]
  2775. yield from self.http.patch(url, json=payload, bucket='move_role')
  2776.  
  2777. @asyncio.coroutine
  2778. def edit_role(self, server, role, **fields):
  2779. """|coro|
  2780.  
  2781. Edits the specified :class:`Role` for the entire :class:`Server`.
  2782.  
  2783. The :class:`Role` object is not directly modified afterwards until the
  2784. corresponding WebSocket event is received.
  2785.  
  2786. All fields except ``server`` and ``role`` are optional. To change
  2787. the position of a role, use :func:`move_role` instead.
  2788.  
  2789. .. versionchanged:: 0.8.0
  2790. Editing now uses keyword arguments instead of editing the :class:`Role` object directly.
  2791.  
  2792. Parameters
  2793. -----------
  2794. server : :class:`Server`
  2795. The server the role belongs to.
  2796. role : :class:`Role`
  2797. The role to edit.
  2798. name : str
  2799. The new role name to change to.
  2800. permissions : :class:`Permissions`
  2801. The new permissions to change to.
  2802. colour : :class:`Colour`
  2803. The new colour to change to. (aliased to color as well)
  2804. hoist : bool
  2805. Indicates if the role should be shown separately in the online list.
  2806. mentionable : bool
  2807. Indicates if the role should be mentionable by others.
  2808.  
  2809. Raises
  2810. -------
  2811. Forbidden
  2812. You do not have permissions to change the role.
  2813. HTTPException
  2814. Editing the role failed.
  2815. """
  2816.  
  2817. colour = fields.get('colour')
  2818. if colour is None:
  2819. colour = fields.get('color', role.colour)
  2820.  
  2821. payload = {
  2822. 'name': fields.get('name', role.name),
  2823. 'permissions': fields.get('permissions', role.permissions).value,
  2824. 'color': colour.value,
  2825. 'hoist': fields.get('hoist', role.hoist),
  2826. 'mentionable': fields.get('mentionable', role.mentionable)
  2827. }
  2828.  
  2829. yield from self.http.edit_role(server.id, role.id, **payload)
  2830.  
  2831. @asyncio.coroutine
  2832. def delete_role(self, server, role):
  2833. """|coro|
  2834.  
  2835. Deletes the specified :class:`Role` for the entire :class:`Server`.
  2836.  
  2837. Parameters
  2838. -----------
  2839. server : :class:`Server`
  2840. The server the role belongs to.
  2841. role : :class:`Role`
  2842. The role to delete.
  2843.  
  2844. Raises
  2845. --------
  2846. Forbidden
  2847. You do not have permissions to delete the role.
  2848. HTTPException
  2849. Deleting the role failed.
  2850. """
  2851.  
  2852. yield from self.http.delete_role(server.id, role.id)
  2853.  
  2854. @asyncio.coroutine
  2855. def _replace_roles(self, member, roles):
  2856. yield from self.http.replace_roles(member.id, member.server.id, roles)
  2857.  
  2858. @asyncio.coroutine
  2859. def add_roles(self, member, *roles):
  2860. """|coro|
  2861.  
  2862. Gives the specified :class:`Member` a number of :class:`Role` s.
  2863.  
  2864. You must have the proper permissions to use this function.
  2865.  
  2866. The :class:`Member` object is not directly modified afterwards until the
  2867. corresponding WebSocket event is received.
  2868.  
  2869. Parameters
  2870. -----------
  2871. member : :class:`Member`
  2872. The member to give roles to.
  2873. \*roles
  2874. An argument list of :class:`Role` s to give the member.
  2875.  
  2876. Raises
  2877. -------
  2878. Forbidden
  2879. You do not have permissions to add roles.
  2880. HTTPException
  2881. Adding roles failed.
  2882. """
  2883.  
  2884. new_roles = utils._unique(role.id for role in itertools.chain(member.roles, roles))
  2885. yield from self._replace_roles(member, new_roles)
  2886.  
  2887. @asyncio.coroutine
  2888. def remove_roles(self, member, *roles):
  2889. """|coro|
  2890.  
  2891. Removes the :class:`Role` s from the :class:`Member`.
  2892.  
  2893. You must have the proper permissions to use this function.
  2894.  
  2895. The :class:`Member` object is not directly modified afterwards until the
  2896. corresponding WebSocket event is received.
  2897.  
  2898. Parameters
  2899. -----------
  2900. member : :class:`Member`
  2901. The member to revoke roles from.
  2902. \*roles
  2903. An argument list of :class:`Role` s to revoke the member.
  2904.  
  2905. Raises
  2906. -------
  2907. Forbidden
  2908. You do not have permissions to revoke roles.
  2909. HTTPException
  2910. Removing roles failed.
  2911. """
  2912. new_roles = [x.id for x in member.roles]
  2913. for role in roles:
  2914. try:
  2915. new_roles.remove(role.id)
  2916. except ValueError:
  2917. pass
  2918.  
  2919. yield from self._replace_roles(member, new_roles)
  2920.  
  2921. @asyncio.coroutine
  2922. def replace_roles(self, member, *roles):
  2923. """|coro|
  2924.  
  2925. Replaces the :class:`Member`'s roles.
  2926.  
  2927. You must have the proper permissions to use this function.
  2928.  
  2929. This function **replaces** all roles that the member has.
  2930. For example if the member has roles ``[a, b, c]`` and the
  2931. call is ``client.replace_roles(member, d, e, c)`` then
  2932. the member has the roles ``[d, e, c]``.
  2933.  
  2934. The :class:`Member` object is not directly modified afterwards until the
  2935. corresponding WebSocket event is received.
  2936.  
  2937. Parameters
  2938. -----------
  2939. member : :class:`Member`
  2940. The member to replace roles from.
  2941. \*roles
  2942. An argument list of :class:`Role` s to replace the roles with.
  2943.  
  2944. Raises
  2945. -------
  2946. Forbidden
  2947. You do not have permissions to revoke roles.
  2948. HTTPException
  2949. Removing roles failed.
  2950. """
  2951.  
  2952. new_roles = utils._unique(role.id for role in roles)
  2953. yield from self._replace_roles(member, new_roles)
  2954.  
  2955. @asyncio.coroutine
  2956. def create_role(self, server, **fields):
  2957. """|coro|
  2958.  
  2959. Creates a :class:`Role`.
  2960.  
  2961. This function is similar to :class:`edit_role` in both
  2962. the fields taken and exceptions thrown.
  2963.  
  2964. Returns
  2965. --------
  2966. :class:`Role`
  2967. The newly created role. This not the same role that
  2968. is stored in cache.
  2969. """
  2970.  
  2971. data = yield from self.http.create_role(server.id)
  2972. role = Role(server=server, **data)
  2973.  
  2974. # we have to call edit because you can't pass a payload to the
  2975. # http request currently.
  2976. yield from self.edit_role(server, role, **fields)
  2977. return role
  2978.  
  2979. @asyncio.coroutine
  2980. def edit_channel_permissions(self, channel, target, overwrite=None):
  2981. """|coro|
  2982.  
  2983. Sets the channel specific permission overwrites for a target in the
  2984. specified :class:`Channel`.
  2985.  
  2986. The ``target`` parameter should either be a :class:`Member` or a
  2987. :class:`Role` that belongs to the channel's server.
  2988.  
  2989. You must have the proper permissions to do this.
  2990.  
  2991. Examples
  2992. ----------
  2993.  
  2994. Setting allow and deny: ::
  2995.  
  2996. overwrite = discord.PermissionOverwrite()
  2997. overwrite.read_messages = True
  2998. overwrite.ban_members = False
  2999. yield from client.edit_channel_permissions(message.channel, message.author, overwrite)
  3000.  
  3001. Parameters
  3002. -----------
  3003. channel : :class:`Channel`
  3004. The channel to give the specific permissions for.
  3005. target
  3006. The :class:`Member` or :class:`Role` to overwrite permissions for.
  3007. overwrite: :class:`PermissionOverwrite`
  3008. The permissions to allow and deny to the target.
  3009.  
  3010. Raises
  3011. -------
  3012. Forbidden
  3013. You do not have permissions to edit channel specific permissions.
  3014. NotFound
  3015. The channel specified was not found.
  3016. HTTPException
  3017. Editing channel specific permissions failed.
  3018. InvalidArgument
  3019. The overwrite parameter was not of type :class:`PermissionOverwrite`
  3020. or the target type was not :class:`Role` or :class:`Member`.
  3021. """
  3022.  
  3023. overwrite = PermissionOverwrite() if overwrite is None else overwrite
  3024.  
  3025.  
  3026. if not isinstance(overwrite, PermissionOverwrite):
  3027. raise InvalidArgument('allow and deny parameters must be PermissionOverwrite')
  3028.  
  3029. allow, deny = overwrite.pair()
  3030.  
  3031. if isinstance(target, Member):
  3032. perm_type = 'member'
  3033. elif isinstance(target, Role):
  3034. perm_type = 'role'
  3035. else:
  3036. raise InvalidArgument('target parameter must be either Member or Role')
  3037.  
  3038. yield from self.http.edit_channel_permissions(channel.id, target.id, allow.value, deny.value, perm_type)
  3039.  
  3040. @asyncio.coroutine
  3041. def delete_channel_permissions(self, channel, target):
  3042. """|coro|
  3043.  
  3044. Removes a channel specific permission overwrites for a target
  3045. in the specified :class:`Channel`.
  3046.  
  3047. The target parameter follows the same rules as :meth:`edit_channel_permissions`.
  3048.  
  3049. You must have the proper permissions to do this.
  3050.  
  3051. Parameters
  3052. ----------
  3053. channel : :class:`Channel`
  3054. The channel to give the specific permissions for.
  3055. target
  3056. The :class:`Member` or :class:`Role` to overwrite permissions for.
  3057.  
  3058. Raises
  3059. ------
  3060. Forbidden
  3061. You do not have permissions to delete channel specific permissions.
  3062. NotFound
  3063. The channel specified was not found.
  3064. HTTPException
  3065. Deleting channel specific permissions failed.
  3066. """
  3067. yield from self.http.delete_channel_permissions(channel.id, target.id)
  3068.  
  3069. # Voice management
  3070.  
  3071. @asyncio.coroutine
  3072. def move_member(self, member, channel):
  3073. """|coro|
  3074.  
  3075. Moves a :class:`Member` to a different voice channel.
  3076.  
  3077. You must have proper permissions to do this.
  3078.  
  3079. Note
  3080. -----
  3081. You cannot pass in a :class:`Object` instead of a :class:`Channel`
  3082. object in this function.
  3083.  
  3084. Parameters
  3085. -----------
  3086. member : :class:`Member`
  3087. The member to move to another voice channel.
  3088. channel : :class:`Channel`
  3089. The voice channel to move the member to.
  3090.  
  3091. Raises
  3092. -------
  3093. InvalidArgument
  3094. The channel provided is not a voice channel.
  3095. HTTPException
  3096. Moving the member failed.
  3097. Forbidden
  3098. You do not have permissions to move the member.
  3099. """
  3100.  
  3101. if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
  3102. raise InvalidArgument('The channel provided must be a voice channel.')
  3103.  
  3104. yield from self.http.move_member(member.id, member.server.id, channel.id)
  3105.  
  3106. @asyncio.coroutine
  3107. def join_voice_channel(self, channel):
  3108. """|coro|
  3109.  
  3110. Joins a voice channel and creates a :class:`VoiceClient` to
  3111. establish your connection to the voice server.
  3112.  
  3113. After this function is successfully called, :attr:`voice` is
  3114. set to the returned :class:`VoiceClient`.
  3115.  
  3116. Parameters
  3117. ----------
  3118. channel : :class:`Channel`
  3119. The voice channel to join to.
  3120.  
  3121. Raises
  3122. -------
  3123. InvalidArgument
  3124. The channel was not a voice channel.
  3125. asyncio.TimeoutError
  3126. Could not connect to the voice channel in time.
  3127. ClientException
  3128. You are already connected to a voice channel.
  3129. OpusNotLoaded
  3130. The opus library has not been loaded.
  3131.  
  3132. Returns
  3133. -------
  3134. :class:`VoiceClient`
  3135. A voice client that is fully connected to the voice server.
  3136. """
  3137. if isinstance(channel, Object):
  3138. channel = self.get_channel(channel.id)
  3139.  
  3140. if getattr(channel, 'type', ChannelType.text) != ChannelType.voice:
  3141. raise InvalidArgument('Channel passed must be a voice channel')
  3142.  
  3143. server = channel.server
  3144.  
  3145. if self.is_voice_connected(server):
  3146. raise ClientException('Already connected to a voice channel in this server')
  3147.  
  3148. log.info('attempting to join voice channel {0.name}'.format(channel))
  3149.  
  3150. def session_id_found(data):
  3151. user_id = data.get('user_id')
  3152. guild_id = data.get('guild_id')
  3153. return user_id == self.user.id and guild_id == server.id
  3154.  
  3155. # register the futures for waiting
  3156. session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found)
  3157. voice_data_future = self.ws.wait_for('VOICE_SERVER_UPDATE', lambda d: d.get('guild_id') == server.id)
  3158.  
  3159. # request joining
  3160. yield from self.ws.voice_state(server.id, channel.id)
  3161. session_id_data = yield from asyncio.wait_for(session_id_future, timeout=10.0, loop=self.loop)
  3162. data = yield from asyncio.wait_for(voice_data_future, timeout=10.0, loop=self.loop)
  3163.  
  3164. kwargs = {
  3165. 'user': self.user,
  3166. 'channel': channel,
  3167. 'data': data,
  3168. 'loop': self.loop,
  3169. 'session_id': session_id_data.get('session_id'),
  3170. 'main_ws': self.ws
  3171. }
  3172.  
  3173. voice = VoiceClient(**kwargs)
  3174. try:
  3175. yield from voice.connect()
  3176. except asyncio.TimeoutError as e:
  3177. try:
  3178. yield from voice.disconnect()
  3179. except:
  3180. # we don't care if disconnect failed because connection failed
  3181. pass
  3182. raise e # re-raise
  3183.  
  3184. self.connection._add_voice_client(server.id, voice)
  3185. return voice
  3186.  
  3187. def is_voice_connected(self, server):
  3188. """Indicates if we are currently connected to a voice channel in the
  3189. specified server.
  3190.  
  3191. Parameters
  3192. -----------
  3193. server : :class:`Server`
  3194. The server to query if we're connected to it.
  3195. """
  3196. voice = self.voice_client_in(server)
  3197. return voice is not None
  3198.  
  3199. def voice_client_in(self, server):
  3200. """Returns the voice client associated with a server.
  3201.  
  3202. If no voice client is found then ``None`` is returned.
  3203.  
  3204. Parameters
  3205. -----------
  3206. server : :class:`Server`
  3207. The server to query if we have a voice client for.
  3208.  
  3209. Returns
  3210. --------
  3211. :class:`VoiceClient`
  3212. The voice client associated with the server.
  3213. """
  3214. return self.connection._get_voice_client(server.id)
  3215.  
  3216. def group_call_in(self, channel):
  3217. """Returns the :class:`GroupCall` associated with a private channel.
  3218.  
  3219. If no group call is found then ``None`` is returned.
  3220.  
  3221. Parameters
  3222. -----------
  3223. channel: :class:`PrivateChannel`
  3224. The group private channel to query the group call for.
  3225.  
  3226. Returns
  3227. --------
  3228. Optional[:class:`GroupCall`]
  3229. The group call.
  3230. """
  3231. return self.connection._calls.get(channel.id)
  3232.  
  3233. # Miscellaneous stuff
  3234.  
  3235. @asyncio.coroutine
  3236. def application_info(self):
  3237. """|coro|
  3238.  
  3239. Retrieve's the bot's application information.
  3240.  
  3241. Returns
  3242. --------
  3243. :class:`AppInfo`
  3244. A namedtuple representing the application info.
  3245.  
  3246. Raises
  3247. -------
  3248. HTTPException
  3249. Retrieving the information failed somehow.
  3250. """
  3251. data = yield from self.http.application_info()
  3252. return AppInfo(id=data['id'], name=data['name'],
  3253. description=data['description'], icon=data['icon'],
  3254. owner=User(**data['owner']))
  3255.  
  3256. @asyncio.coroutine
  3257. def get_user_info(self, user_id):
  3258. """|coro|
  3259.  
  3260. Retrieves a :class:`User` based on their ID. This can only
  3261. be used by bot accounts. You do not have to share any servers
  3262. with the user to get this information, however many operations
  3263. do require that you do.
  3264.  
  3265. Parameters
  3266. -----------
  3267. user_id: str
  3268. The user's ID to fetch from.
  3269.  
  3270. Returns
  3271. --------
  3272. :class:`User`
  3273. The user you requested.
  3274.  
  3275. Raises
  3276. -------
  3277. NotFound
  3278. A user with this ID does not exist.
  3279. HTTPException
  3280. Fetching the user failed.
  3281. """
  3282. data = yield from self.http.get_user_info(user_id)
  3283. return User(**data)
Add Comment
Please, Sign In to add comment