|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import datetime |
| 5 | +import asyncio |
| 6 | +import warnings |
| 7 | +from typing import List, Callable |
| 8 | + |
| 9 | +from botbuilder.schema import (Activity, ActivityTypes, |
| 10 | +
6D40
ChannelAccount, ConversationAccount, |
| 11 | + ResourceResponse, ConversationReference) |
| 12 | +from botbuilder.core.bot_context import BotContext |
| 13 | +from botbuilder.core.bot_adapter import BotAdapter |
| 14 | + |
| 15 | + |
| 16 | +class ConsoleAdapter(BotAdapter): |
| 17 | + """ |
| 18 | + Lets a user communicate with a bot from a console window. |
| 19 | +
|
| 20 | + :Example: |
| 21 | + import asyncio |
| 22 | + from botbuilder.core import ConsoleAdapter |
| 23 | +
|
| 24 | + async def logic(context): |
| 25 | + await context.send_activity('Hello World!') |
| 26 | +
|
| 27 | + adapter = ConsoleAdapter() |
| 28 | + loop = asyncio.get_event_loop() |
| 29 | + if __name__ == "__main__": |
| 30 | + try: |
| 31 | + loop.run_until_complete(adapter.process_activity(logic)) |
| 32 | + except KeyboardInterrupt: |
| 33 | + pass |
| 34 | + finally: |
| 35 | + loop.stop() |
| 36 | + loop.close() |
| 37 | + """ |
| 38 | + def __init__(self, reference: ConversationReference = None): |
| 39 | + super(ConsoleAdapter, self).__init__() |
| 40 | + |
| 41 | + self.reference = ConversationReference(channel_id='console', |
| 42 | + user=ChannelAccount(id='user', name='User1'), |
| 43 | + bot=ChannelAccount(id='bot', name='Bot'), |
| 44 | + conversation=ConversationAccount(id='convo1', name='', is_group=False), |
| 45 | + service_url='') |
| 46 | + |
| 47 | + # Warn users to pass in an instance of a ConversationReference, otherwise the parameter will be ignored. |
| 48 | + if reference is not None and not isinstance(reference, ConversationReference): |
| 49 | + warnings.warn('ConsoleAdapter: `reference` argument is not an instance of ConversationReference and will ' |
| 50 | + 'be ignored.') |
| 51 | + else: |
| 52 | + self.reference.channel_id = getattr(reference, 'channel_id', self.reference.channel_id) |
| 53 | + self.reference.user = getattr(reference, 'user', self.reference.user) |
| 54 | + self.reference.bot = getattr(reference, 'bot', self.reference.bot) |
| 55 | + self.reference.conversation = getattr(reference, 'conversation', self.reference.conversation) |
| 56 | + self.reference.service_url = getattr(reference, 'service_url', self.reference.service_url) |
| 57 | + # The only attribute on self.reference without an initial value is activity_id, so if reference does not |
| 58 | + # have a value for activity_id, default self.reference.activity_id to None |
| 59 | + self.reference.activity_id = getattr(reference, 'activity_id', None) |
| 60 | + |
| 61 | + self._next_id = 0 |
| 62 | + |
| 63 | + async def process_activity(self, logic: Callable): |
| 64 | + """ |
| 65 | + Begins listening to console input. |
| 66 | + :param logic: |
| 67 | + :return: |
| 68 | + """ |
| 69 | + while True: |
| 70 | + msg = input() |
| 71 | + if msg is None: |
| 72 | + pass |
| 73 | + else: |
| 74 | + self._next_id += 1 |
| 75 | + activity = Activity(text=msg, |
| 76 | + channel_id='console', |
| 77 | + from_property=ChannelAccount(id='user', name='User1'), |
| 78 | + recipient=ChannelAccount(id='bot', name='Bot'), |
| 79 | + conversation=ConversationAccount(id='Convo1'), |
| 80 | + type=ActivityTypes.message, |
| 81 | + timestamp=datetime.datetime.now(), |
| 82 | + id=str(self._next_id)) |
| 83 | + |
| 84 | + activity = BotContext.apply_conversation_reference(activity, self.reference, True) |
| 85 | + context = BotContext(self, activity) |
| 86 | + await self.run_middleware(context, logic) |
| 87 | + |
| 88 | + async def send_activities(self, context: BotContext, activities: List[Activity]): |
| 89 | + """ |
| 90 | + Logs a series of activities to the console. |
| 91 | + :param context: |
| 92 | + :param activities: |
| 93 | + :return: |
| 94 | + """ |
| 95 | + if context is None: |
| 96 | + raise TypeError('ConsoleAdapter.send_activities(): `context` argument cannot be None.') |
| 97 | + if type(activities) != list: |
| 98 | + raise TypeError('ConsoleAdapter.send_activities(): `activities` argument must be a list.') |
| 99 | + if len(activities) == 0: |
| 100 | + raise ValueError('ConsoleAdapter.send_activities(): `activities` argument cannot have a length of 0.') |
| 101 | + |
| 102 | + async def next_activity(i: int): |
| 103 | + responses = [] |
| 104 | + |
| 105 | + if i < len(activities): |
| 106 | + responses.append(ResourceResponse()) |
| 107 | + a = activities[i] |
| 108 | + |
| 109 | + if a.type == 'delay': |
| 110 | + await asyncio.sleep(a.delay) |
| 111 | + await next_activity(i + 1) |
| 112 | + elif a.type == ActivityTypes.message: |
| 113 | + if a.attachments is not None and len(a.attachments) > 0: |
| 114 | + append = '(1 attachment)' if len(a.attachments) == 1 else f'({len(a.attachments)} attachments)' |
| 115 | + print(f'{a.text} {append}') |
| 116 | + else: |
| 117 | + print(a.text) |
| 118 | + await next_activity(i + 1) |
| 119 | + else: |
| 120 | + print(f'[{a.type}]') |
| 121 | + await next_activity(i + 1) |
| 122 | + else: |
| 123 | + return responses |
| 124 | + |
| 125 | + await next_activity(0) |
| 126 | + |
| 127 | + async def delete_activity(self, context: BotContext, reference: ConversationReference): |
| 128 | + """ |
| 129 | + Not supported for the ConsoleAdapter. Calling this method or `BotContext.delete_activity()` |
| 130 | + will result an error being returned. |
| 131 | + :param context: |
| 132 | + :param reference: |
| 133 | + :return: |
| 134 | + """ |
| 135 | + raise NotImplementedError('ConsoleAdapter.delete_activity(): not supported.') |
| 136 | + |
| 137 | + async def update_activity(self, context: BotContext, activity: Activity): |
| 138 | + """ |
| 139 | + Not supported for the ConsoleAdapter. Calling this method or `BotContext.update_activity()` |
| 140 | + will result an error being returned. |
| 141 | + :param context: |
| 142 | + :param activity: |
| 143 | + :return: |
| 144 | + """ |
| 145 | + raise NotImplementedError('ConsoleAdapter.update_activity(): not supported.') |
0 commit comments